-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Checking Generic Type at Runtime #13053
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
Comments
This behavior is correct because class IntSubclass(int): ...
i1 = IntSubclass(0)
i2 = increment(i1)
# At runtime, i2 is an instance of 'int', not 'IntSubclass'.
print(type(i2)) # <class 'int'> |
That makes sense. Thank you for explainging! My actual use case is more complicated, however. Instead of from typing import TypeVar
T = TypeVar("T")
class Dummy:
def __init__(self):
self.state: int = 0
def mutate_state(self):
self.state += 1
def handle(obj: T) -> T:
if isinstance(obj, Dummy):
obj.mutate_state()
return obj
else:
return obj I get the same error:
Even though |
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: @overload
def handle(obj: Dummy) -> Dummy: ...
@overload
def handle(obj: T) -> T: ...
def handle(obj: T | Dummy) -> T | Dummy:
if isinstance(obj, Dummy):
obj.mutate_state()
return obj
else:
return obj |
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 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). |
Yeah, this is not a bug. The revised example is going to be fixed in #19183 |
Bug Report
When checking the type of a generic, mypy reports an error when (as far as I understand), I am still following the type contract I set.
To Reproduce
Expected Behavior
I expect there to be no error because if
obj
is anint
, then returning anint
is the correct behavior.Actual Behavior
Mypy reports an error.
Your Environment
--strict
mypy.ini
(and other config files): no other configThe text was updated successfully, but these errors were encountered: