Skip to content

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

Closed

Description

@carljm

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.

Activity

  1. carljm commented on Jul 18, 2017

    @carljm
    MemberAuthor

    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"

  2. ilevkivskyi commented on Jul 18, 2017

    @ilevkivskyi
    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.

  3. camio commented on Aug 26, 2017

    @camio

    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")
    
  4. ilevkivskyi commented on Sep 29, 2017

    @ilevkivskyi
    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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions