"""Base class for parameter files."""from__future__importannotationsfromtypingimportTypeVar,Generic,castfromabcimportabstractmethodfromdataclassesimportInitVarfromparamdb._param_data._dataclassesimportParamDataclasstry:importpandasaspdPANDAS_INSTALLED=TrueexceptImportError:PANDAS_INSTALLED=FalseDataT=TypeVar("DataT")
[docs]classParamFile(ParamDataclass,Generic[DataT]):""" Subclass of :py:class:`ParamDataclass`. Base class for parameter file classes. Subclasses must implement the abstract methods :py:meth:`_save_data` and :py:meth:`_load_data`. For example:: class ParamText(ParamFile[str]): def _save_data(self, path: str, data: str) -> None: with open(path, "w", encoding="utf-8") as f: f.write(data) def _load_data(self, path: str) -> str: with open(path, "r", encoding="utf-8") as f: return f.read() """path:str"""Path to the file represented by this object."""initial_data:InitVar[DataT|None]=None# pylint: disable-next=arguments-differdef__post_init__(self,initial_data:DataT|None)->None:super().__post_init__()ifinitial_dataisnotNone:self.update_data(initial_data)@abstractmethoddef_save_data(self,path:str,data:DataT)->None:"""Save the given data in a file at the given path."""@abstractmethoddef_load_data(self,path:str)->DataT:"""Load data from the file at the given path."""@propertydefdata(self)->DataT:"""Data stored in the file represented by this object."""returnself._load_data(self.path)
[docs]defupdate_data(self,data:DataT)->None:"""Update the data stored within the file represented by this object."""self._save_data(self.path,data)self._update_last_updated()
ifPANDAS_INSTALLED:
[docs]classParamDataFrame(ParamFile[pd.DataFrame]):""" Subclass of :py:class:`ParamFile`. Parameter data Pandas DataFrame, stored in a Pickle file. This class will only be defined if Pandas is installed. """def_load_data(self,path:str)->pd.DataFrame:returncast(pd.DataFrame,pd.read_pickle(path))def_save_data(self,path:str,data:pd.DataFrame)->None:data.to_pickle(path)