Skip to content

Optional[NamedTuple] makes mypy think a branch is unreachable #3601

Closed
@ilinum

Description

@ilinum

In the following example, the else branch is not typechecked. As far as I've been able to narrow it down, it seems like it has to do with NamedTuple.

from typing import Optional, NamedTuple, List

NamedTup = NamedTuple('NamedTup', [('a', str)])


class Foo:
    def __init__(self) -> None:
        self.x = get_optional()
        if self.x:
            # this is typechecked
            f: str = 2  # error: Incompatible types in assignment
        else:
            # this is not typechecked
            j: str = 2  # no error
            self.mypy_does_not_typecheck_this()  # no error
            reveal_type(j)  # no error


def get_optional() -> Optional[NamedTup]:
    return None


Foo()

Here is the output from mypy and python.

$ mypy n.py
n.py:11: error: Incompatible types in assignment (expression has type "int", variable has type "str")
$ python3 n.py
Traceback (most recent call last):
  File "n.py", line 23, in <module>
    Foo()
  File "n.py", line 15, in __init__
    self.mypy_does_not_typecheck_this()  # no error
AttributeError: 'Foo' object has no attribute 'mypy_does_not_typecheck_this'

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions