下面的程序可以工作,但给出了一个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)
我做错了什么?
替换 object
与 Type[object]
神秘的工作。
解决方案:
你使用的是 变量型 错位,应与 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
本文来自投稿,不代表实战宝典立场,如若转载,请注明出处:https://www.shizhanbaodian.com/40504.html