-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
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
Getting a union from an and
expression
#16565
Comments
I think mypy is doing the right thing here. The # If `a` is `None`, the result of `a and 8` will be `None`
print(None and 8) # Prints "None"
# If `a` is `Literal[0]`, then `a and 8` will evaluate to `Literal[0]`
print(0 and 8) # Prints "0"
If `a` is any other `int` value, then `a and 8` will evaluate to `Literal[8]`
print(1 and 8) # Prints "8" For comparison, pyright evaluates the type of |
Sorry, I oversimplified it while coming up with the minimal reproducer, it was probably meant to be the inverse of that. I've just updated the original issue with a slightly more complex example, which better matches the code in the linked PR. |
Yeah, I agree that the modified example demonstrates a bug (or at least a missing feature) in mypy. @AlexWaygood, if you agree, could you reopen the issue? |
Couldn't it be a Connection whose |
That's theoretically possible if the class is not |
It appears that mypy isn't smart enough to deduce "if @Final without bool or len, then always true", but otherwise adding As for a workaround, either seems to work
|
Would there be an easy way to make this suggestion in the error output? Our example is actually not Final, we just didn't think of that edge case. |
Assuming you don't want to change
def make_request() -> requests.Response | dict:
resp = requests.get('http://example.com')
return resp and resp.json() Maybe Keeping context and suggesting when the |
We decided to go with the first option, as we may have made similar assumptions elsewhere in the code and it keeps the logic simple. Both solutions would be useful to suggest in this context.
Yeah, I figured that might be difficult as you'd need to know the cause was from the code further up. |
#16566 was merged so starting from mypy 1.8(?) adding |
Bug Report
I'd hope there's already an issue for this, but couldn't find one.
When using
and
, mypy infers a union from both sides when the truthy evaluation makes it impossible.Actual code trigerring the error: https://github.com/aio-libs/aiohttp/pull/7879/files#diff-720910fd022b9ba8b7ddf0cb446ce5e1afe443f4287ad26a1eb4dc4b5b5f4508R944
To Reproduce
Expected Behavior
protocol can't be Connection, so this error shouldn't happen.
Your Environment
The text was updated successfully, but these errors were encountered: