以类型化函数为例,
def add1(x: int, y: int) -> int:
return x + y
和一般功能。
def add2(x,y):
return x + y
使用 mypy 进行类型检查add1
add1("foo", "bar")
会导致
error: Argument 1 to "add1" has incompatible type "str"; expected "int"
error: Argument 2 to "add2" has incompatible type "str"; expected "int"
上不同输入类型的输出add2
,
>>> add2(1,2)
3
>>> add2("foo" ,"bar")
'foobar'
>>> add2(["foo"] ,['a', 'b'])
['foo', 'a', 'b']
>>> add2(("foo",) ,('a', 'b'))
('foo', 'a', 'b')
>>> add2(1.2, 2)
3.2
>>> add2(1.2, 2.3)
3.5
>>> add2("foo" ,['a', 'b'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in add
TypeError: cannot concatenate 'str' and 'list' objects
请注意,这add2
是一般情况。ATypeError
仅在行执行后引发,您可以通过类型检查来避免这种情况。类型检查可让您从一开始就识别类型不匹配。
优点:
- 更容易调试 == 节省时间
- 减少手动类型检查
- 更简单的文档
缺点: