首页 > 解决方案 > 仅针对任意类的 Python 类型提示(不是类实例或任何其他非类类型)

问题描述

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

但是不知道使用typing模块注释类参数类型的正确方法。我不认为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

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

标签: pythontype-hintingpython-typing

解决方案


'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 方类型检查器,请参阅Python 3.5 中的类型提示是什么?.


推荐阅读