You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This behavior is correct because isinstance(obj, int) does not guarantee that obj is an int; it simply guarantees that it's a subtype of int. However, the __add__ method for int always returns an int, not a subtype of int.
classIntSubclass(int): ...
i1=IntSubclass(0)
i2=increment(i1)
# At runtime, i2 is an instance of 'int', not 'IntSubclass'.print(type(i2)) # <class 'int'>
Thanks for the suggestion; I will try it in my full case but I was hoping to avoid all the extra boilerplate! (I have half a dozen classes that have special isinstance cases.)
I'll leave this open as a bug in mypy. If I have time, maybe I will be able to look into why this happens (probably not).
Activity
erictraut commentedon Jul 1, 2022
This behavior is correct because
isinstance(obj, int)does not guarantee thatobjis anint; it simply guarantees that it's a subtype ofint. However, the__add__method forintalways returns anint, not a subtype ofint.samuelstevens commentedon Jul 2, 2022
That makes sense. Thank you for explainging!
My actual use case is more complicated, however. Instead of
int, I have some objects of a class that call some methods. Something like:I get the same error:
Even though
objmight just be a subclass ofDummy, I am still returningobjdirectly which is still of typeT. So shouldn't this be error-free?erictraut commentedon Jul 2, 2022
Yes, your revised sample is type safe. I don't think mypy should emit an error in this case. By comparison, pyright does not.
Here's a workaround for mypy:
samuelstevens commentedon Jul 2, 2022
Thanks for the suggestion; I will try it in my full case but I was hoping to avoid all the extra boilerplate! (I have half a dozen classes that have special
isinstancecases.)I'll leave this open as a bug in mypy. If I have time, maybe I will be able to look into why this happens (probably not).
ilevkivskyi commentedon May 31, 2025
Yeah, this is not a bug. The revised example is going to be fixed in #19183