[英]What is wrong with using object as a type in Python?
The following program works, but gives a MyPy error:以下程序有效,但给出了 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 complains: 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)
What am I doing wrong?我究竟做错了什么?
Replacing object
with Type[object]
mysteriously works.用Type[object]
替换object
神秘地起作用。
You're using the type variable in the wrong place, it should be used with element
not types
.您在错误的地方使用了类型变量,它应该与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
The problem was that the default value has to fit for every possible substitution for T
.问题是默认值必须适合T
的所有可能替换。 Since it doesn't the right way to solve this is to define overloads, one with the Type[T]
producing Optional[T]
and one with Literal[object]
and producing Any
.由于解决此问题的正确方法是定义重载,一种是Type[T]
产生Optional[T]
,另一种是Literal[object]
并产生Any
。 Then in the combined declaration, the default can be provided.然后在组合声明中,可以提供默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.