python / python/mypy

`NamedTuple`s cannot have nested classes

Open
#15,775 1 comment 0 reactions 1 assignee View on GitHub

@sobolevn is already working on this.

Since Jul 29, 2023.

bug topic-named-tuple
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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 https://github.com/python/mypy/issues/15752

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.