Python 仅针对任意 classes 的类型提示(不是 class 实例或任何其他非 class 类型)

Python type hint for arbitrary classes only (not class instances or any other non-class types)

我有一种方法可以检查和处理任意 classes 的源(仅限 classes,而不是 class 实例或任何其他非 class 类型). classes 可以来自任何标准库、第三方库或用户定义的 classes。

但不知道使用 typing 模块注释 class 参数类型的正确方法。我不认为 typing.Type 是正确的,因为它也适用于对象:

>>> class A: pass
>>> a = A()

>>> def test(cl: typing.Type) -> typing.Type:
...     return type(cl)

>>> test(A)
>>> type
>>> isinstance(A, typing.Type)
>>> True

>>> test(a)
>>> type
>>> isinstance(A, typing.Type)
>>> False

>>> test('A')
>>> str
>>> isinstance(A, typing.Type)
>>> False

注释应该这样工作吗?注释参数不应该限制方法的调用只识别正确类型的参数吗?

'Type'确实是正确的使用方法。例如,如果您尝试使用 mypy...

等类型检查器对以下程序进行类型检查
from typing import Type

class A: pass

# To be even more precise, have the type signature be
# '(cls: Type[T]) -> Type[Type[T]]' where T is some TypeVar.
def test(cls: Type) -> Type:
    return type(cls)

a = A()

test(A)
test(a)
test('A')

...您最终遇到以下错误,我相信这是您所期望的:

test.py:13: error: Argument 1 to "test" has incompatible type "A"; expected "Type[Any]"
test.py:14: error: Argument 1 to "test" has incompatible type "str"; expected "Type[Any]"
Found 2 errors in 1 file (checked 1 source file)

如果您询问为什么 Python 本身不检查这些类型提示以及为什么您需要使用第 3 方类型检查器,请参阅