I have the following classes:
from typing import Any, TypedDict
class RawDict(TypedDict):
key1: str
key2: int
class MyDict(dict):
def __init__(self, data: RawDict) -> None:
self._validate(data)
super().__init__(data)
def _validate(self, data: RawDict) -> None:
# validate data and raise if invalid
def some_other_method(self) -> Any:
# do anything interesting
I would like to be able to annotate every instance of MyDict
with the RawDict
type. Currently, it results in a typing error (MyPy 0.930):
var: RawDict = MyDict({"key1": "value", "key2": 1})
# error: Incompatible types in assignment (expression has type "MyDict", variable has type "RawDict")
On the other hand, if we annotate it with MyDict
, we won’t know the exact types of values in that dict
:
var: MyDict = MyDict({"key1": "value", "key2": 1})
var1 = var["key1"] # recognized as Any
var2 = var["key2"] # recognized as Any
In my actual implementation, the RawDict
type is more complex, e.g. it’s keys are other TypedDict
s or lists of TypedDict
s.
How can I combine MyDict
and RawDict
so that my variables “know” about their actual keys and available methods?
I tried inheriting class MyDict(RawDict):
, but it made MyPy fail with error: Invalid statement in TypedDict definition; expected "field_name: field_type"
.
I’m using Python 3.8.