28 lines
753 B
Python
28 lines
753 B
Python
|
import dataclasses
|
||
|
import json
|
||
|
from dataclasses import dataclass
|
||
|
|
||
|
|
||
|
@dataclass(init=False)
|
||
|
class DataclassBase:
|
||
|
def __init__(self, **kwargs):
|
||
|
names = set([f.name for f in dataclasses.fields(self)])
|
||
|
for k, v in kwargs.items():
|
||
|
if k in names:
|
||
|
setattr(self, k, v)
|
||
|
|
||
|
|
||
|
class Singleton(type):
|
||
|
_instances = {}
|
||
|
|
||
|
def __call__(cls, *args, **kwargs):
|
||
|
if cls not in cls._instances:
|
||
|
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
|
||
|
return cls._instances[cls]
|
||
|
|
||
|
|
||
|
class DataclassJSONEncoder(json.JSONEncoder):
|
||
|
def default(self, o):
|
||
|
if dataclasses.is_dataclass(o):
|
||
|
return dataclasses.asdict(o)
|
||
|
return super().default(o)
|