Files
vaiola/pythonapp/Libs/ConfigDataClass.py
Bacruru Sakaguchi 9e5e214944 initial commit
2025-09-12 17:10:13 +07:00

53 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import json
import atexit
from dataclasses import dataclass, asdict, fields
from typing import Any, Dict
from pathlib import Path
@dataclass
class Config:
filename: str
autosave: bool = False
def __post_init__(self):
# Загружаем значения из файла при создании экземпляра
self.load()
# Регистрируем автоматическое сохранение при завершении программы
if self.autosave:
atexit.register(self.save)
def load(self) -> None:
"""Загружает значения полей из файла"""
try:
if Path(self.filename).exists():
with open(self.filename, 'r') as f:
data = json.load(f)
for field in fields(self):
if field.name in data and field.name != 'filename':
setattr(self, field.name, data[field.name])
except Exception as e:
print(f"Error loading config: {e}")
def save(self) -> None:
"""Сохраняет текущие значения полей в файл"""
try:
# Преобразуем объект в словарь, исключая поле filename
data = asdict(self)
data.pop('filename', None)
# Создаем директорию, если она не существует
Path(self.filename).parent.mkdir(parents=True, exist_ok=True)
# Сохраняем в файл с кастомным сериализатором для Path объектов
with open(self.filename, 'w') as f:
json.dump(data, f, indent=4, default=self._json_serializer)
except Exception as e:
print(f"Error saving config: {e}")
def _json_serializer(self, obj: Any) -> Any:
"""Кастомный сериализатор для объектов, которые не могут быть сериализованы по умолчанию"""
if isinstance(obj, Path):
return str(obj)
raise TypeError(f"Object of type {type(obj).__name__} is not JSON serializable")