-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Order of methods affects validity of instance variables #1016
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
Comments
Basically this is a similar issue to #481. The reason is that type inference goes from top to bottom in a file, and when you refer to something that hasn't been inferred yet mypy complains. I haven't prioritized this because it's usuall;y easy to work around by giving an explicit annotation:
Another workaround (but this can change semantics):
The general fix would be run type checking in multiple passes. We wouldn't report errors when mypy can't determine the type immediately. Instead, the enclosing function would be added to a worklist, and after doing a full type checker run over a module (or a set of cyclically dependent modules) we'd type check items in the worklist again, and we'd repeat this until we worklist doesn't get any smaller in an iteration or we hit some max number of iterations. |
A partial, quick fix would be to run simple type inference as part of semantic analysis and infer types for variables where the initializer is a simple expression (and where initialization doesn't happen in an if statement, for example). So we could infer these types always, independent of order:
These would cover a non-trivial subset of initializers. Not sure whether it's worth it to special case these, however. |
Oh wow, I would never have guessed that adding |
Yeah, this is a pretty bad issue. I thought about this some more and solving this for a single file (i.e. not for cyclically dependent modules) shouldn't be too hard, maybe one or two days of work -- but it could be more, as changing this would change a bunch of subtle implicit assumptions in the implementation. Inferring types from literals should be a few hours to implement. As a quick fix, I'll try adding a more informative error message (something like |
Mypy now does 2-pass type inference within a single file. |
Consider:
This fails:
This is apparently because bar() hasn't been analyzed yet when foo() is being analyzed. If we swap the definitions the program is clean.
The text was updated successfully, but these errors were encountered: