首页 > 解决方案 > 在 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)

我究竟做错了什么?

objectType[object]神秘的作品代替。

标签: pythonmypypython-typing

解决方案


您在错误的地方使用了类型变量,它应该与elementnot一起使用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

推荐阅读