python 2 和 3 中的类型检查 python NamedTuple
typechecking python NamedTuple in both python 2 and 3
我有一个 Python 代码,可与 python2 和 python3 一起使用并使用 mypy。
我设法使用以下 非常复杂 方法对我的命名元组进行了类型检查:
try:
from typing import TYPE_CHECKING
except ImportError:
TYPE_CHECKING = False
if TYPE_CHECKING:
from typing import NamedTuple
Foo = NamedTuple("Foo", [("foo", int)])
else:
from collections import namedtuple
Foo = namedtuple("Foo", ["foo"])
correct = Foo(foo= 1)
incorrect = Foo(foo= "bla") # error: Argument 1 to "Foo" has incompatible type "str"; expected "int"
注意:使用类似这样的方法只定义一次字段是行不通的:
foo_typed_fields = [("foo", int)]
foo_fields = [f[0] for f in foo_typed_fields]
问题:有更简单的方法吗?
是——为 Python 2 安装官方 typing module backport(例如 pip install typing
或 pip2 install typing
),然后只需执行以下操作:
from typing import NamedTuple
Foo = NamedTuple("Foo", [("foo", int)])
我有一个 Python 代码,可与 python2 和 python3 一起使用并使用 mypy。 我设法使用以下 非常复杂 方法对我的命名元组进行了类型检查:
try:
from typing import TYPE_CHECKING
except ImportError:
TYPE_CHECKING = False
if TYPE_CHECKING:
from typing import NamedTuple
Foo = NamedTuple("Foo", [("foo", int)])
else:
from collections import namedtuple
Foo = namedtuple("Foo", ["foo"])
correct = Foo(foo= 1)
incorrect = Foo(foo= "bla") # error: Argument 1 to "Foo" has incompatible type "str"; expected "int"
注意:使用类似这样的方法只定义一次字段是行不通的:
foo_typed_fields = [("foo", int)]
foo_fields = [f[0] for f in foo_typed_fields]
问题:有更简单的方法吗?
是——为 Python 2 安装官方 typing module backport(例如 pip install typing
或 pip2 install typing
),然后只需执行以下操作:
from typing import NamedTuple
Foo = NamedTuple("Foo", [("foo", int)])