如何检查 Python 对象是否满足类型约束?
How can I check whether a Python object satisfies a type constraint?
假设我在 dataclass
:
上有这种类型约束
from dataclasses import dataclass
from typing import Sequence
from numbers import Integral
@dataclass
class Coefficients:
coefs: Sequence[Integral]
现在我想知道对象[1, 2, 3]
是否满足这个类型约束。我想知道这一点,因为我 coding/designing,不一定在运行时,所以静态检查器解决方案或运行时解决方案都可以。
我试过 isinstance()
但它不适用于参数化类型:
$ mypy -c 'from typing import Sequence; from numbers import Integral; isinstance([1, 2, 3], Sequence[Integral])'
<string>:1: error: Parameterized generics cannot be used with class or instance checks
$ python -c 'from typing import Sequence; from numbers import Integral; isinstance([1, 2, 3], Sequence[Integral])'
[...]
TypeError: Subscripted generics cannot be used with class and instance checks
一般来说,我想知道如何根据 任意 类型注释检查对象;虽然我可以轻松查找 List
是否是 Sequence
和 int
是否是 Integral
,但稍后我可能想检查更复杂的结构。我该怎么做?
需要的类型可以注解,直接运行mypy就可以了。 Mypy 有一个 open issue 关于支持 numbers
模块的数字塔。
mypy -c 'from typing import Sequence
from numbers import Integral
x: Sequence[Integral]
x = [1, 2, 3]'
<string>:4: error: List item 0 has incompatible type "int"; expected "Integral"
<string>:4: error: List item 1 has incompatible type "int"; expected "Integral"
<string>:4: error: List item 2 has incompatible type "int"; expected "Integral"
假设我在 dataclass
:
from dataclasses import dataclass
from typing import Sequence
from numbers import Integral
@dataclass
class Coefficients:
coefs: Sequence[Integral]
现在我想知道对象[1, 2, 3]
是否满足这个类型约束。我想知道这一点,因为我 coding/designing,不一定在运行时,所以静态检查器解决方案或运行时解决方案都可以。
我试过 isinstance()
但它不适用于参数化类型:
$ mypy -c 'from typing import Sequence; from numbers import Integral; isinstance([1, 2, 3], Sequence[Integral])'
<string>:1: error: Parameterized generics cannot be used with class or instance checks
$ python -c 'from typing import Sequence; from numbers import Integral; isinstance([1, 2, 3], Sequence[Integral])'
[...]
TypeError: Subscripted generics cannot be used with class and instance checks
一般来说,我想知道如何根据 任意 类型注释检查对象;虽然我可以轻松查找 List
是否是 Sequence
和 int
是否是 Integral
,但稍后我可能想检查更复杂的结构。我该怎么做?
需要的类型可以注解,直接运行mypy就可以了。 Mypy 有一个 open issue 关于支持 numbers
模块的数字塔。
mypy -c 'from typing import Sequence
from numbers import Integral
x: Sequence[Integral]
x = [1, 2, 3]'
<string>:4: error: List item 0 has incompatible type "int"; expected "Integral"
<string>:4: error: List item 1 has incompatible type "int"; expected "Integral"
<string>:4: error: List item 2 has incompatible type "int"; expected "Integral"