'How to enforce TypedDict structure in a class
I was wondering how to utilize TypedDict in my own class in an ORM-like application im building. Here is my best try:
I have the following TypedDict:
class ConcreteOptions(TypedDict):
one: str
two: str
(Now the non-functioning part) Theres a class like this:
class Database(Generic[VT]):
def __init__(self, options: Dict[str, Any]):
self.options = cast(VT, options)
def __getitem__(self, k: str) -> VT:
return self.options[k]
An instance of that class would get initialized like this:
opts: ConcreteOptions = {"one": "1", "two": "2"}
db: Database[ConcreteOptions] = Database(opts)
The desired behavior would allow me to get items from the instance via
val_one = db["one"]
val_two = db["two"]
while having correct type inference and intellisense in the IDE.
Having the ability to use Database[SomeOptions] is the key of what im trying to achieve as thats the way the end user will enforce some types on the underlying object.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
