-
-
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
False positive and negative with lambda narrowing #16056
Comments
Mypy is basically correct here, although it should probably also complain about the lambda (looks a little tricky to do). See https://mypy.readthedocs.io/en/stable/common_issues.html#narrowing-and-inner-functions. Note when not at top level you can't mutate locals from outside so it's sounder to have heuristics that avoid false positives: #15133 This is why if you put your entire code snippet inside a checked function, it will pass. |
Thank you very much for the explanation, that was a pretty bad oversight on my part. |
I agree that it should pass in this case, but it apparently does not. The following code still results in a type error for the lambda. This seems like a mypy bug. def func(x: int | None) -> None:
if isinstance(x, int):
def f() -> int:
return x + 2 # No Error
(lambda: x + 2)() # Error |
OP's example does work when put in a function as-is. The difference seems to be with immediately evaluated lambdas:
|
Reopened and retitled the issue. The false positive is Eric's case, the false negative is for the lambda in:
|
Both should be fixed by #16407 |
Bug Report
Type narrowing does not work correctly in function bodies. Even if the type is narrowed down in the context in which a function or a lambda is defined, that narrowing seems to be 'forgotten' within the function body.
To Reproduce
Gist URL: https://gist.github.com/mypy-play/41141b62a73edc56b6561088adea8ebf
Playground URL: https://mypy-play.net/?mypy=latest&python=3.11&flags=strict&gist=41141b62a73edc56b6561088adea8ebf
Expected Behavior
No errors in the lines where errors are actually reported. Type narrowing should make all of these expressions valid.
Actual Behavior
The errors given in the comments.
Your Environment
--strict
.mypy.ini
(and other config files): None.The text was updated successfully, but these errors were encountered: