python - 在 Python 中使用 object 作为类型有什么问题?
问题描述
以下程序有效,但给出了 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
not一起使用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
推荐阅读
- java - Struts 2(在 jsp 的迭代器之外使用 Select 会导致逗号附加在选择值上而不是重置它)
- gradle - 从kotlin的gradle中获取项目实例
- mongodb - 魔方JS | 如何连接从 MongoDB 数组创建的两个表?
- html - 如何使用引导选项卡指向另一个网站?
- powershell-core - PowerShell Core 可以使用 Windows 终端而不是 pwsh.exe 控制台吗?
- javascript - JavaScript:TypeError:未定义不是对象
- python - Python:从 GeoDataFrame 绘制 LineStrings 时出现 cmap 问题
- laravel - Sentry 错误日志在 laravel mix 中不起作用
- scala - 如何避免在 Spark (2.4) SQL 中自动转换 ArrayType - Scala 2.11
- codenameone - 当指针在别处按下时如何防止多行文本字段滚动