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
{{ message }}
Repository navigation
Type narrowing of 'TypeVar' causes '[return-value]' error #15151
One way to think about it is that "v didn't change" suggesting that v should narrow not to an Instance but to a TypeVarType bound to str. Or maybe it should "narrow" not v itself but T so that the function itself, within that branch, would now be happy with return "foo".
That would be incorrect, since foo can be a subtype of str.
What am I missing?
fromtypingimportTypeVarT=TypeVar('T')
classmystr(str):
passdeff(v: T) ->T:
ifisinstance(v, str):
returnmystr("bar") # at this point, T is narrowed to TypeVar('T', bound=str)returnvvalue=f("foo")
reveal_type(value) # N: Revealed type is "builtins.str"
IIUC, value being deemed a str here is fine, even though it might end up a mystr.
from typing import TypeVar
T = TypeVar('T')
class mystr(str): ...
class otherstr(str): ...
def f(v: T) -> T:
if isinstance(v, str):
return mystr("bar")
return v
value = f(otherstr("foo"))
reveal_type(value) # oops, revealed type is "__main__.otherstr"
Activity
ikonst commentedon Apr 30, 2023
One way to think about it is that "
vdidn't change" suggesting thatvshould narrow not to anInstancebut to aTypeVarTypebound tostr. Or maybe it should "narrow" notvitself butTso that the function itself, within that branch, would now be happy withreturn "foo".JelleZijlstra commentedon Jun 4, 2023
That would be incorrect, since
foocan be a subtype of str.ikonst commentedon Jun 6, 2023
What am I missing?
IIUC,
valuebeing deemed astrhere is fine, even though it might end up amystr.hauntsaninja commentedon Jun 6, 2023
isinstancebranch #18658 as a duplicate of this issueT | Sequence[T]#19202 as a duplicate of this issueNarrow type variable bounds in binder (python#19183)