[英]I keep getting the error: object of type 'NoneType' has no len() in python, what's wrong with the code?
[英]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
神秘地起作用。
您在錯誤的地方使用了類型變量,它應該與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在這里解決了這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.