【问题标题】:Python type hint for arbitrary classes only (not class instances or any other non-class types)仅针对任意类的 Python 类型提示(不是类实例或任何其他非类类型)
【发布时间】:2020-06-12 17:02:23
【问题描述】:

我有一个方法可以检查和处理任意类的来源(仅限类,而不是类实例或任何其他非类类型)。这些类可以来自任何标准库、第 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

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

【问题讨论】:

  • 类型提示只是......提示......它们向您的IDE提示对象可能的类型。但它们不是运行时代码的一部分,它们不强制对象类型必须是特定的
  • 谢谢,没关系。我想也许有一个仅适用于类的特殊类型提示会很有用。
  • 与生成器 (typing.Generator) 和迭代器 (typing.Iterator) 的类型提示相同,即使生成器是迭代器。
  • isinstance((x for x in range(10)), typing.Iterator) -> True
  • 抱歉,我删除了我的评论以重写它,genartors 返回迭代器,但它们不在其中自我迭代器

标签: python type-hinting python-typing


【解决方案1】:

'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 方类型检查器,请参阅 What are type hints in Python 3.5?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-03
    • 2011-04-28
    • 2022-11-02
    • 2018-12-05
    • 2023-03-29
    • 2021-04-10
    • 2020-07-24
    • 1970-01-01
    相关资源
    最近更新 更多