I have a Python code that works with both python2 and python3 and uses mypy. I managed to have my namedtuples typechecked with the following really convoluted method:
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"
Note: using something like this to define fields only once does not work:
foo_typed_fields = [("foo", int)]
foo_fields = [f[0] for f in foo_typed_fields]
Question: Is there a simpler way to do this ?