Python >=3.5:在运行时检查类型注释 [英] Python >=3.5: Checking type annotation at runtime
问题描述
typing
模块(或任何其他模块)是否展示了一个 API 来在运行时对变量进行类型检查,类似于 isinstance()
但了解isinstance()
中定义的类型类代码>打字?
Does the typing
module (or any other module) exhibit an API to typecheck a variable at runtime, similar to isinstance()
but understanding the type classes defined in typing
?
我想运行类似于:
from typing import List
assert isinstance([1, 'bob'], List[int]), 'Wrong type'
推荐答案
typing
模块中没有这样的功能,而且很可能永远不会有.
There is no such function in the typing
module, and most likely there won't ever be.
检查一个对象是否是一个类的实例——这仅仅意味着这个对象是由类的构造函数创建的"——是测试一些标记的简单问题.
Checking whether an object is an instance of a class - which only means "this object was created by the class' constructor" - is a simple matter of testing some tagging.
然而,检查一个对象是否是一个类型的实例"并不一定是可判定的:
However, checking whether an object is an "instance" of a type is not necessarily decidable:
assert isinstance(foo, Callable[[int], str]), 'Wrong type'
尽管检查 foo
的类型注释很容易(假设它不是 lambda
),但根据莱斯定理,检查它是否符合它们通常是不可判定的.
Although it is easy to inspect the typing annotations of foo
(assuming it's not a lambda
), checking whether it complies to them is generally undecidable, by Rice's theorem.
即使使用更简单的类型,例如 List[int]
,测试也很容易变得效率太低,无法用于除最小的玩具示例之外的任何其他内容.
Even with simpler types, such as List[int]
the test will easily become far too inefficient to be used for anything but the smallest toy examples.
xs = set(range(10000))
xs.add("a")
xs.pop()
assert isinstance(xs, Set[int]), 'Wrong type'
<小时>
允许类型检查器以相对有效的方式执行此操作的技巧是保守的:类型检查器试图证明 foo
总是返回 int
.如果失败,它会拒绝该程序,即使该程序可能是有效的,即这个函数很可能会被拒绝,尽管它是完全安全的:
The trick that allows type checker to perform this operation in a relatively efficient way, is to be conservative: the type checker tries to prove that foo
always return int
. If it fails, it rejects the program, even though the program may be valid, i.e. this function is likely to be rejected, although it is perfectly safe:
def foo() -> int:
if "a".startswith("a"):
return 1
return "x"
这篇关于Python >=3.5:在运行时检查类型注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!