-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
Inference from unannotated functions #4455
Comments
I would actually say this is a bug. We shouldn't use d = {} # We should require an annotation here, if the second assignment below is absent...
def g():
d['x'] = 1
d[1] = 'x' # ...instead of inferring 'Dict[Any, Any]' that may be unsafe. |
IMO it is unclear that the error is at the last line. I would expect that line to define the type, and the error to be inside the function, since it is unannotated and therefore assumed to be too clever for the type checker. I am confused though. I agree that we shouldn't use (implicit) Any for partial types, but from the discussion on #4434 I understood that this is by design. This issue was meant to be more general: I am trying to understand how things should behave. What are the rules. |
I was probably not very clear in my example. At least one of the two assignments is probably erroneous. But it would be safer to use the second for inference. The only downside of this is that after annotating the function, an error will appear in previously valid code. But this is better than the current (clearly unsafe) behavior. In case if there is no second assignment we should give a normal
I don't think current behavior is really intentional, @JukkaL may correct me. |
The current behavior seems accidental or at least not very well thought out. I think that it would be better to require all parts of a partial type definition to be located within a single scope. So this shouldn't be valid: d = {} # We should require an annotation here
def f():
# This is a different scope from the initial assignment so can't affect the partial type
d['x'] = 1 In the original example, we should probably use the second assignment for inference ( |
Jukka, I agree. So - what does mypy do inside unannotated functions? |
Here are some things (probably incomplete):
Much of this isn't very principled, to be honest. |
Seems like the not-inconsistent part is straight-forward semantic analysis. |
Mypy uses the body of unannotated functions for inference and to understand what attributes an object has. For example:
I couldn't find any mention of it on the docs. I think this behaviour needs to be documented. Perhaps as a separate section, to make it searchable.
Related: #4434 #4409
The text was updated successfully, but these errors were encountered: