python - 仅针对任意类的 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
注释应该以这种方式工作吗?注释的参数不应该限制方法的调用以仅识别正确类型的参数吗?
解决方案
'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 中的类型提示是什么?.
推荐阅读
- vba - 我需要使用 MS Access 读取 .txt 文件,修改记录并添加标题记录
- docker - 在 Windows 10 上连接到 docker 容器内的 minikube 上的入口失败
- lodash - 车轮事件上的 lodash 油门延迟。领先的选项=真正的不工作?
- javascript - 为什么我的 React 功能组件会破坏我的 GSAP 动画?
- python - 有什么方法可以计算 NetworkX 中节点属性的总和
- sql - 获取与 2 个 ID 匹配但包含来自第 3 个 ID 的所有记录的重复记录
- ruby-on-rails - Rails - 协会别名解析为零?
- typescript - 如何在 Typescript 中正确处理 React Native 和浏览器实现
- google-sheets - 使用 Google 表格作为 plotlyjs 的数据源
- r - 如何在配方中添加自定义步骤