'mypy error for function returning TypeVar based on Type[T] argument
I have a function that validates variable based on TypedDict
declaration at runtime. I want it to perform validation, raise exception on error and set return type otherwise.
Essentially, I have this:
T = TypeVar("T")
def validated(data: Any, DataType: Type[T]) -> T:
validate(data, DataType) # this raises exception if data is not valid as T
return data
class MyDataType(TypedDict):
a: int
b: str
d = validated(get_data(), MyDataType)
reveal_type(d)
d["a"] + 10
d["b"] + "suffix"
After validated
call variable d
should be typed as MyDataType
, reveal_type(d)
shows it. Hence the last two lines are type-safe. However, mypy
complains:
temp.py:29: note: Revealed type is "temp.MyDataType"
temp.py:30: error: Unsupported operand types for + ("object" and "int")
temp.py:31: error: "object" has no attribute "lower"
What am I doing wrong?
UPD
I f I add explicit typing to d
(d: MyDataType = validated(get_data(), MyDataType)
) I get even more mysterious messages:
temp.py:28: error: Incompatible types in assignment (expression has type "MyDataType", variable has type "MyDataType")
temp.py:33: note: Revealed type is "TypedDict('temp.MyDataType', {'a': builtins.int, 'b': builtins.str})"
UPD 2
Seems like the same issue has already been reported: https://github.com/python/mypy/issues/12310
TL;DR: it's not a bug, TypedDict is not valid in this context (although the error message might have been clearer)
Software versions
- mypy: 0.950
- python: 3.9.12
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|