python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.57k stars 2.84k forks source link

Conditional statements don't work inside a NamedTuple class body #18187

Open tungol opened 4 days ago

tungol commented 4 days ago

Bug Report

Mypy generates an error when conditional statements are used inside the class body of a NamedTuple. This is mostly a problem in typeshed.

To Reproduce

from typing import NamedTuple
import sys

class Foo(NamedTuple):
    bar: str
    if sys.version_info >= (3, 10):
        def extra(self) -> str:
            return ""
    else:
        def other(self) -> str:
            return ""

Mypy Playground

Expected Behavior

Mypy generates no error.

Actual Behavior

main.py:6: error: Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"  [misc]
Found 1 error in 1 file (checked 1 source file)