简体   繁体   English

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

[英]What is wrong with using object as a type in Python?

The following program works, but gives a MyPy error:以下程序有效,但给出了 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 complains: 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)

What am I doing wrong?我究竟做错了什么?

Replacing object with Type[object] mysteriously works.Type[object]替换object神秘地起作用。

You're using the type variable in the wrong place, it should be used with element not types .您在错误的地方使用了类型变量,它应该与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

The problem was that the default value has to fit for every possible substitution for T .问题是默认值必须适合T的所有可能替换。 Since it doesn't the right way to solve this is to define overloads, one with the Type[T] producing Optional[T] and one with Literal[object] and producing Any .由于解决此问题的正确方法是定义重载,一种是Type[T]产生Optional[T] ,另一种是Literal[object]并产生Any Then in the combined declaration, the default can be provided.然后在组合声明中,可以提供默认值。

This was addressed by Guido here . Guido在这里解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM