1

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 ?

1 Answer 1

1

Yes -- install the official typing module backport for Python 2 (e.g. pip install typing or pip2 install typing), then just do the following:

from typing import NamedTuple

Foo = NamedTuple("Foo", [("foo", int)])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.