Skip to content

NamedTuples cannot have nested classes #15775

Open
@sobolevn

Description

@sobolevn

Python allows class definitions inside NamedTuple bodies:

>>> from typing import NamedTuple
>>> class A(NamedTuple):
...     class B: ...
... 
>>> A.B
<class '__main__.A.B'>
>>> A().B
<class '__main__.A.B'>

But, mypy does not allow this:

from typing import NamedTuple

class A(NamedTuple):
    class B: ...  # E: Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"

reveal_type(A.B)  # E: "type[A]" has no attribute "B"
# N: Revealed type is "Any"

I think that this is a bug that needs to be solved, because we don't have any reason not to allow this (my existing patch shows that semanal and typechecker are happy with allowing these classes).

This is the root cause of #15752

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions