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
fromtypingimportType, TypeVar, cast, OptionalT=TypeVar('T')
defread(t: Type[T], text: str) ->T:
returncast(T, None) # dummy return just for example codedefmain() ->None:
a=read(Optional[int], "10")
reveal_type(a)
b=read(int, "10")
reveal_type(b)
The output:
$ mypy test.py
test.py:11: error: Argument 1 to "read" has incompatible type "object"; expected "Type[<nothing>]"
Found 1 error in 1 file (checked 1 source file)
This made me notice that, while I thought T was being inferred correctly in 0.770, it wasn't:
$ mypy test.py
test.py:12: note: Revealed type is 'Any'
test.py:14: note: Revealed type is 'builtins.int*'
I use this in some code along with typing_inspect to read input into dataclasses, using their types as a schema. The runtime behaviour is correct, but while I thought mypy was correctly inferring the type, when it is Optional, it isn't.
Maybe there is a better way to write this kind of generic code, though, and I'm on the wrong path here. Although I would expect this to work.
Optional is not meant to be used like this. It is not a reified type (not usable in a runtime context like this). You would need to unwrap the Optional[T] into either None or T.
Activity
emmatyping commentedon Jun 3, 2020
Optional is not meant to be used like this. It is not a reified type (not usable in a runtime context like this). You would need to unwrap the
Optional[T]into eitherNoneorT.