簡體   English   中英

在 Python 中使用 object 作為類型有什么問題?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM