Skip to content

Non-optional outer variable becomes optional in inner function #5048

@mjayfrancis

Description

@mjayfrancis

Mypy (0.600, default options - i.e. strict optional enabled) seems to get confused about the optionality of 'foo' in the below code:

from typing import Optional

class Foo:
    def bar(self) -> None:
         pass

def outer(foo: Optional[Foo]=None):
    foo = Foo()

    def inner() -> None:
        foo.bar()

reveal_type() shows that it correctly realises that 'foo' is no longer optional after the assignment in outer(), but for some reason it has become optional again in inner():

$ mypy foo.py 
foo.py:11: error: Item "None" of "Optional[Foo]" has no attribute "bar"

I know it's possible to overcome this by doing e.g. assert foo is not None, but it seems this case should work as is.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions