-
Notifications
You must be signed in to change notification settings - Fork 1.5k
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
Variable set in with
block reported as possibly unbound in certain cases
#7009
Comments
This behavior is intended, so I don't consider this a bug — at least not in pyright. Context managers can be written such that they "swallow" all exceptions that occur within their scope. Other context managers do not do this and allow any exceptions to bubble up. By convention, type checkers determine the difference by looking at the defined return type of the Your options:
|
This seems kind of counterintuitive. At least with Pylance basic type checking, if a type is unknown Pyright makes the related type checking logic more lax and allows things that might be incorrect. However, in this case Pytight seems to make the type checking more strict when the type is unknown. It seems to me more appropriate and consistent (or at least more practical, given that many libraries lack proper typing) to assume that exceptions are not swallowed, if the return type of |
A bad assumption in either direction will produce false positives. One isn't "more lax" than the other. The |
Though in this specific case it seems that Pyright is technically correct because of a combination of a few things:
I think I'm going to try opening an issue with matplotlib in the hopes that they can make the return type more specific to avoid this problem. |
@erictraut Currently an |
When I was writing this logic in pyright, I matched mypy's behavior. However, I don't know if mypy's behavior in this case was intended or accidental. It strikes me as inconsistent. For example, mypy treats a return type of This is clearly an area that should be specified in the typing spec, and I'm hopeful that we'll get to it in the near future. It's on a long list of items that the recently-formed "typing council" (of which I'm a member) needs to prioritize. |
Intended or not, it is convenient that this makes type checking assume that a general |
Describe the bug
When creating variables inside a
with
block wherematplotlib.pyplot.ion()
ormatplotlib.pyplot.ioff()
is the context manager, these variables are reported as possibly unbound after thewith
block.To the best of my knowledge this is just plain wrong. The
with
block body always runs and the variables are always bound. I would expect Pylance/Pyright to treat them as such.This does not seem to happen with other context managers.
Code or Screenshots
Environment data
The text was updated successfully, but these errors were encountered: