类型错误:打字。Any 不能与 isinstance() 一起使用

Xoc*_*lli 3 python typing

我想知道为什么 Python 的输入模块不支持isinstance(<obj>, Any)并引发TypeError. 我希望它总是会回来True。它不总是返回有什么具体原因吗True

  • 此处引发 TypeError 。
  • 类型错误示例:
>>> from typing import Any
>>> isinstance(1, Any)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/peter/miniconda3/envs/prefect_utils/lib/python3.9/typing.py", line 338, in __instancecheck__
    raise TypeError(f"{self} cannot be used with isinstance()")
TypeError: typing.Any cannot be used with isinstance()
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 6

Any文档字符串似乎说明了原因:

"""Special type indicating an unconstrained type.

- Any is compatible with every type.
- Any assumed to have all methods.
- All values assumed to be instances of Any.

Note that all the above statements are true from the point of view of
static type checkers. At runtime, Any should not be used with instance
or class checks.
"""

def __instancecheck__(self, obj):
    raise TypeError("Any cannot be used with isinstance().")

def __subclasscheck__(self, cls):
    raise TypeError("Any cannot be used with issubclass().")

Run Code Online (Sandbox Code Playgroud)

如果这些对象没有提供实例或子类应提供的确切内容,则将这些对象视为实际实例或子类可能会导致问题。相反,它们“假装”这样一个事实:它们可以是任何东西,但不会因为在类型层次结构中以这种方式处理而造成损害。