Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NamedTuple with a TypeVar #588

Closed
mehdigmira opened this issue Oct 23, 2018 · 3 comments
Closed

NamedTuple with a TypeVar #588

mehdigmira opened this issue Oct 23, 2018 · 3 comments

Comments

@mehdigmira
Copy link

Hello,

This is a question concerning NamedTuples. I'm using python 3.5.

Is there a way to create a namedtuple that relies on a typevar ?

I've tried this:

from typing import Optional, TypeVar, NamedTuple, Dict, Tuple, Generic

MetaDataT = TypeVar("MetaDataT")

def f(m: MetaDataT):
    State = NamedTuple("State", [("metadata", MetaDataT), ("new", bool), ("update", MetaDataT)])

But mypy complains by saying: error: 'MetaDataT' is a type variable and only valid in type context

So I tried to declare State outside of the function such as:

from typing import Optional, TypeVar, NamedTuple, Dict, Tuple, Generic

MetaDataT = TypeVar("MetaDataT")

State = NamedTuple("State", [("metadata", MetaDataT), ("new", bool), ("update", MetaDataT)])

But this time mypy complains by saying: error: Invalid type "debug.MetaDataT"

I guess something like this coul work:

class S(NamedTuple, Generic[MetaDataT]):
     pass

But I'm using python 3.5 and this syntax is not supported.

@JelleZijlstra
Copy link
Member

Mypy doesn't allow generic namedtuples; see python/mypy#685.

@JelleZijlstra
Copy link
Member

(This is a limitation in mypy though, not in the type system itself, so no need to keep this issue open.)

@ilevkivskyi
Copy link
Member

Yes, this is a duplicate of python/mypy#685.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants