-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Unexpected error when narrowing TypeVar #14045
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
I should note that there are some other cases which make this complicated: from typing import TypeVar, reveal_type
T = TypeVar("T")
def f(a: T, b: T) -> T:
return a
reveal_type(f("1", 2))
Ooh. Except, maybe not: from typing import TypeVar, reveal_type, NewType
T = TypeVar("T")
Special = NewType("Special", str)
TheSpecial = Special("Hello")
def f(a: T) -> T:
if isinstance(a, str):
return "Goodbye"
return a
reveal_type(f(TheSpecial)) If Maybe this is not trivially possible. |
Is it the same issue as #13956? |
I believe so. |
Closing as duplicate of #10817 |
Bug report
I ran into this recently and @glyph came up with a very elegant minimal working example:
Basically, if you have a function that takes a typevar and you narrow it using an
isinstance
check,mypy
decides that the concrete type does not match the generic type from the signature, despite the fact that the concrete type is just the narrowed generic.The best workaround I've found is to return
cast(T, s)
. Glyph and I both tried playing around with overloads and couldn't find something to work around the issue other than just a cast.The text was updated successfully, but these errors were encountered: