В моем понимании коды, я часто использую метод класса для создания экземпляра объекта attrs из файла json. Например:
Код: Выделить всё
from cattrs.preconf.json import make_converter
from attrs import field, define, validators
from enum import StrEnum, auto
from pathlib import Path
class Colors(StrEnum):
BLUE = auto()
RED = auto()
GREEN = auto()
@define
class A:
color: Colors = field(validator=validators.instance_of(Colors))
value: int = field(validator=validators.instance_of(int))
@classmethod
def from_json_file(cls, path: Path):
with open(path, 'r') as f:
data = json.load(f)
return cls(color=Colors(data["color"]), value=data["value"])
Код: Выделить всё
@classmethod
def from_json_file(cls, path: Path):
json_converter = make_converter()
return json_converter.loads(path.read_text(), cls)
Подробнее здесь: https://stackoverflow.com/questions/792 ... n-object-f
Мобильная версия