Skip to content

self-referential NamedTuple leads to spurious "incompatible types" with List[<nothing>] #3731

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

Closed
carljm opened this issue Jul 18, 2017 · 4 comments
Labels

Comments

@carljm
Copy link
Member

carljm commented Jul 18, 2017

This code typechecks cleanly:

from typing import List, NamedTuple

class Person(NamedTuple):
    name: str
    age: int
 
people: List[Person] = []

But add a self-referential attribute to the NamedTuple:

from typing import List, NamedTuple

class Person(NamedTuple):
    name: str
    age: int
    kids: List['Person']
 
people: List[Person] = []

And now we get:

namedtuple.py:9: error: Incompatible types in assignment (expression has type List[<nothing>], variable has type List[Person])

If Person is an ordinary class instead of a NamedTuple, the error doesn't appear.

@carljm
Copy link
Member Author

carljm commented Jul 18, 2017

For added fun, if you then do people.append(Person(...)), you get the delightful error message:

namedtuple.py:10: error: Argument 1 to "append" of "list" has incompatible type "Person"; expected "Person"

@ilevkivskyi
Copy link
Member

Sorry, this is an old problem. Also there are similar things with other "synthetic types" TypedDict, NewType, aliases etc. that don't work well in the forward-reference context. I was going to work on this, but didn't get to it yet. I will keep this open, since here you provide use-cases that are not mentioned in other issues.

@camio
Copy link

camio commented Aug 26, 2017

I ran into this issue as well, but the error message I received is slightly different.

class Node(NamedTuple):
    children : List['Node']
    
def first_child(n : Node) -> Node:
    return n.children[0]

I get this error:

test.py:10: error: Incompatible return value type (got "test.Node", expected "Node")

@ilevkivskyi
Copy link
Member

All examples now work correctly, this is also fixed by #3952. Only an (expected) warning about not fully supported recursive type is emitted.

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

No branches or pull requests

3 participants