在 Python 中使用对象作为类型有什么问题?
What is wrong with using object as a type in Python?
以下程序可以运行,但会出现 MyPy 错误:
from typing import Type, TypeVar, Any, Optional
T = TypeVar('T')
def check(element: Any, types: Type[T] = object) -> Optional[T]:
if not isinstance(element, types):
return None
return element
print(check(123, int))
print(check(123, object))
MyPy 抱怨:
main.py:7: error: Incompatible default for argument "types" (default has type "Type[object]", argument has type "Type[T]")
Found 1 error in 1 file (checked 1 source file)
我做错了什么?
用 Type[object]
替换 object
神奇地起作用了。
您在错误的地方使用了 type variable,它应该与 element
一起使用,而不是 types
。
from typing import Optional, Type, TypeVar
T = TypeVar('T')
def check(element: T, types: Type = object) -> Optional[T]:
if not isinstance(element, types):
return None
return element
问题是默认值必须适合每个可能的 T
替换。由于解决这个问题的正确方法是定义重载,一种是 Type[T]
产生 Optional[T]
,另一种是 Literal[object]
产生 Any
。然后在组合声明中,提供默认即可。
Guido here 解决了这个问题。
以下程序可以运行,但会出现 MyPy 错误:
from typing import Type, TypeVar, Any, Optional
T = TypeVar('T')
def check(element: Any, types: Type[T] = object) -> Optional[T]:
if not isinstance(element, types):
return None
return element
print(check(123, int))
print(check(123, object))
MyPy 抱怨:
main.py:7: error: Incompatible default for argument "types" (default has type "Type[object]", argument has type "Type[T]")
Found 1 error in 1 file (checked 1 source file)
我做错了什么?
用 Type[object]
替换 object
神奇地起作用了。
您在错误的地方使用了 type variable,它应该与 element
一起使用,而不是 types
。
from typing import Optional, Type, TypeVar
T = TypeVar('T')
def check(element: T, types: Type = object) -> Optional[T]:
if not isinstance(element, types):
return None
return element
问题是默认值必须适合每个可能的 T
替换。由于解决这个问题的正确方法是定义重载,一种是 Type[T]
产生 Optional[T]
,另一种是 Literal[object]
产生 Any
。然后在组合声明中,提供默认即可。
Guido here 解决了这个问题。