Starting with Python 3.7, there is something called a dataclass:
from dataclasses import dataclass
@dataclass
class Foo:
x: str
However, t
I'd suggest creating a parent class for your dataclasses with a to_json()
method:
import json
from dataclasses import dataclass, asdict
@dataclass
class Dataclass:
def to_json(self) -> str:
return json.dumps(asdict(self))
@dataclass
class YourDataclass(Dataclass):
a: int
b: int
x = YourDataclass(a=1, b=2)
x.to_json() # '{"a": 1, "b": 2}'
This is especially useful if you have other functionality to add to all your dataclasses.