在Python中使用object作为类型有什么错?

2024-05-17 10:57:13 发布

您现在位置: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神秘地起作用


Tags: defaultreturnobjectchecktypeanyerrorelement
2条回答

问题是默认值必须适合T的每个可能的替换。因为解决这个问题的正确方法不是定义重载,一个是使用Type[T]产生Optional[T],另一个是使用Literal[object]和产生Any。然后在组合声明中,可以提供缺省值

Guido here解决了这一问题

您在错误的位置使用了type variable,它应该与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

相关问题 更多 >