Skip to content

Document type inference behavior in case type declaration has (not) initializer #7252

Open
@JukkaL

Description

@JukkaL

In cases like this mypy doesn't narrow down the type in assignment:

x: Union[int, str] = 0
# type of x is Union[int, str] here!

Any assignment after the initial declaration will narrow the type down:

x: Union[int, str]
x = 0
# type of x is int here!

Document this behavior since it can be surprising. The motivation for this is that this behavior makes it easy to override the inferred type for a variable, which is sometimes useful.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions