在使用函数时,我希望确保变量的类型符合预期。如何做到呢?
这里有一个示例伪函数试图在继续其角色之前实现这一点:
def my_print(begin, text, end):
"""Print 'text' in UPPER between 'begin' and 'end' in lower
"""
for i in (begin, text, end):
assert isinstance(i, str), "Input variables should be strings"
out = begin.lower() + text.upper() + end.lower()
print out
def test():
"""Put your test cases here!
"""
assert my_print("asdf", "fssfpoie", "fsodf")
assert not my_print("fasdf", 33, "adfas")
print "All tests passed"
test()
使用assert是否是正确的方法?还是应该使用try/except?
另外,我的assert测试集似乎无法正常工作:S
感谢各位Python开发者。
typing
模块、mypy 和其他工具,但上述说法仍然十分正确:拥有一个静态类型的 Python 将会非常好。 - Evgeny