直接从typing文档中考虑以下typing.TypeVar
的图示:
# mypytest.py
from typing import TypeVar
A = TypeVar("A", str, bytes) # I.e. typing.AnyStr
def longest(x: A, y: A) -> A:
"""Return the longest of two strings."""
# https://docs.python.org/3/library/typing.html
return x if len(x) >= len(y) else y
调用mypy mypytest.py
不会产生任何错误并退出0。在此示例中,目的是A
可以是str
或bytes
,但是返回类型将与传递的类型。
但是,当存在默认参数时,mypy将引发错误:
def longest_v2(x: A = "foo", y: A = "bar") -> A:
return x if len(x) >= len(y) else y
提高:
$ mypy mypytest.py
mypytest.py:11: error: Incompatible default for argument "x" (default has type "str", argument has type "bytes")
mypytest.py:11: error: Incompatible default for argument "y" (default has type "str", argument has type "bytes")
为什么在第二种情况下会发生错误?
带有行号:
1 # mypytest.py
2 from typing import TypeVar
3
4 A = TypeVar("A", str, bytes) # I.e. typing.AnyStr
5
6 def longest(x: A, y: A) -> A:
7 """Return the longest of two strings."""
8 # https://docs.python.org/3/library/typing.html
9 return x if len(x) >= len(y) else y
10
11 def longest_v2(x: A = "foo", y: A = "bar") -> A:
12 return x if len(x) >= len(y) else y