Let's consider I have the following TypedDict:
class A(TypedDict):
a: int
b: int
What is the best practice for setting default values for this class?
I tried to add a constructor but it doesn't seem to work.
class A(TypedDict):
a: int
b: int
def __init__(self):
TypedDict.__init__(self)
a = 0
b = 1
EDIT: I don't want to use dataclass because I need to serialize and deserialize to JSON files and dataclasses have some problem with it.
What do you think?
TypedDictis only for specifying that adictfollows a certain layout, not an actual class. You can of course use aTypedDictto create an instance of that specific layout but it doesn't come with defaults.One possible solution is to add a factory method to the class. You could use this factory method instead to set defaults.
If having a
dictis not a strict requirement then@dataclassis good having small objects with defaults.If you need to create a dictionary from them, you can use
asdict