Funny behaviour with Union[Decimal, int] #1442
Copy link
Copy link
Closed
Labels
bugmypy got something wrongmypy got something wrongfalse-positivemypy gave an error on correct codemypy gave an error on correct codepriority-1-normaltopic-union-types
Description
Considering the following program:
from decimal import Decimal
from typing import Union
def foo(bar: Union[Decimal, int]):
print(Decimal(1) + bar)
print(bar + Decimal(1))
Why does mypy complain in the second print()?
$ mypy foo.py
foo.py: note: In function "foo":
foo.py:6: error: Unsupported operand types for + ("Union[Decimal, int]" and "Decimal")
I'm using mypy 0.3.1 on Python 3.5.1, Ubuntu 16.04.
Metadata
Metadata
Assignees
Labels
bugmypy got something wrongmypy got something wrongfalse-positivemypy gave an error on correct codemypy gave an error on correct codepriority-1-normaltopic-union-types
Activity
gvanrossum commentedon Apr 26, 2016
I'm not sure. I can repro this with the latest mypy from the repo.
refi64 commentedon Apr 26, 2016
@gvanrossum Is this a typeshed bug? Note that
Decimal.__add__is defined withrhsas_Decimal(orUnion[Decimal, int]), but__radd__expects just a normalint.gvanrossum commentedon Apr 26, 2016
But I can't repro it without using a Union.
refi64 commentedon Apr 26, 2016
@gvanrossum Exactly, because
__radd__expects just anint, not a union. Here's an example outside ofDecimal:gvanrossum commentedon Apr 26, 2016
refi64 commentedon Apr 26, 2016
So then the general issue is binary operators, I guess. It seems Mypy sees this:
and tries to look for either
Union[A,B].__add__(C)orC.__radd__, but it should instead look for bothAandBseparately. So it would insteas check for one of the following:A.__add__(C)andB.__add__(C)C.__radd__(A)andC.__radd__(B)This is mostly a guess, though...
JukkaL commentedon Apr 27, 2016
@kirbyfan64 I believe that you are right. The logic for checking binary operations should probably decompose union types early and process each union item independently (and finally combine the results, possibly resulting in another union type).
gvanrossum commentedon Apr 27, 2016
JukkaL commentedon Apr 27, 2016
That may be relevant, but this may also be a separate issue/bug.
Use specific types in dateutil.relativedelta stubs
Use specific types in dateutil.relativedelta stubs
ilevkivskyi commentedon Aug 18, 2018
FWIW this particular example works correctly on master (due to a recent operator overhaul by @Michael0x2a ). We have a separate issue for general union destructuring in operator checks.
ilevkivskyi commentedon Aug 18, 2018
Just for reference, the main issue is #2128