Generic list in NamedTuple in python3.4

Viewed 33

I want to define new type which holds list of generic values. For example (simplified as much as possible):

from typing import NamedTuple, TypeVar, List
T = TypeVar('T')
MyType = NamedTuple('MyType', [('values', List[T])])

but this doesn't work and mypy reports following errors:

a.py:4: error: Type variable "a.T" is unbound
a.py:4: note: (Hint: Use "Generic[T]" or "Protocol[T]" base class to bind "T" inside a class)
a.py:4: note: (Hint: Use "T" in function signature to bind "T" inside a function)
Found 1 error in 1 file (checked 1 source file)

Unfortunately, I need python3.4 compatibility (please don't ask why), so I can't use "dataclass" version.

I tried to ignore it by adding #type: ignore to MyType definition, but then mypy wants to add types even in constructions like this:

def do_stuff(x: MyType) -> None:
    for v in x.values:
        pass

saying: error: Need type annotation for 'v'.

Is there any way to make this work under python3.4 or do I have to keep adding # type: ignore?

0 Answers
Related