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
TypeVar("T") can be anything, unless a type guard hints at something else #16742
According to the docs, a TypeVar("T") can be anything, but type guards hint at something.
To Reproduce
fromtypingimportTypeVarPT=TypeVar("PT")
deff(p: PT) ->PT:
reveal_type(p) # Revealed type is "PT`-1"ifisinstance(p, bool):
reveal_type(p) # Revealed type is "builtins.bool"returnpifisinstance(p, int):
reveal_type(p) # Revealed type is "builtins.int"returnpreveal_type(p) # Revealed type is "PT`-1"returnpf(False) # Incompatible return value type (got "bool", expected "PT")f(0) # Incompatible return value type (got "int", expected "PT")f(.0)
I would expect the above example to pass. But then again, I've opened tickets in the past which proved to be either my own misunderstanding or my own misuse :)
Actual Behavior
main.py:8: note: Revealed type is "PT`-1"
main.py:11: note: Revealed type is "builtins.bool"
main.py:12: error: Incompatible return value type (got "bool", expected "PT") [return-value]
main.py:15: note: Revealed type is "builtins.int"
main.py:16: error: Incompatible return value type (got "int", expected "PT") [return-value]
main.py:18: note: Revealed type is "PT`-1"
Found 2 errors in 1 file (checked 1 source file)
changed the title [-]`TypeVar("T")` can be anything, unless a type guard[/-][+]`TypeVar("T")` can be anything, unless a type guard hints at something else[/+]on Jan 3, 2024
Activity
[-]`TypeVar("T")` can be anything, unless a type guard[/-][+]`TypeVar("T")` can be anything, unless a type guard hints at something else[/+]hauntsaninja commentedon Jan 4, 2024
Thanks for the issue, I think this is a duplicate of #15151. See also #15711 / #15377
alexei commentedon Jan 4, 2024
If a fix isn't planned, then what is the recommended workaround? Cast to
T?hauntsaninja commentedon Jan 4, 2024
Yes, type ignore or cast will work. Definitely a bug so will be fixed
alexei commentedon Jan 4, 2024
Ok, thanks