Python mypy“;参数“”的默认值不兼容;使用关键字arg默认值
考虑以下直接从文档中输入的Python mypy“;参数“”的默认值不兼容;使用关键字arg默认值,python,python-3.x,mypy,python-typing,Python,Python 3.x,Mypy,Python Typing,考虑以下直接从文档中输入的typing.TypeVar示例: 调用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:
typing.TypeVar
示例:
调用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
嗯,那我不能回答。我想说的是签名中
A
的类型必须一致,因此对于字符串的默认参数,如果使用默认值,您将强制其余参数中的A
为字符串,这将导致在传递字节时出现问题。确切地说:“bar”
具有单态类型(str
),但是A
是一种多态类型(可以是str
,也可以是bytes
)。无法指定要用作默认值的多态性值。您可能希望使用Union[str,bytes]
?但是,即使这会绕过检查,它也可能在运行时引发异常。Union[str,bytes]
和TypeVar(“A”,str,bytes)
在行为上是不同的@CristiFatiI我相信如果使用默认值,mypy会强制A
到str
,那就太好了。这是我所期望的行为。另一方面,我希望mypy失败x:str=3
,因为3
无法满足类型约束str
。这与OP的例子不同,str
可以完全满足A
。
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