Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
JukkaL opened this issue Jul 22, 2019 · 3 comments

Comments

@JukkaL
Copy link
Collaborator

JukkaL commented Jul 22, 2019

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.

@ilevkivskyi
Copy link
Member

Related #2008

@tz-earl
Copy link

tz-earl commented Mar 24, 2020

Beginner contributor here. I'd like to add the above explanation by JukkaL to the docs.

Would Common Issues and Solutions be an appropriate place?

@gvanrossum
Copy link
Member

@tz-earl I'm sorry we dropped your question. This is a very busy project, with an all volunteer crew! I think the right place to document this would be a new section in Type inference and type annotations, perhaps right after Explicit types for variables.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants