[docs]classSerialMixin:"""A mixin class providing serialization functionality."""# Use slots so that derived classes also remain slotted# See also: https://www.attrs.org/en/stable/glossary.html#term-slotted-classes__slots__=()
[docs]defto_dict(self)->dict:"""Create an object's dictionary representation. Returns: The dictionary representation of the object. """dct=converter.unstructure(self)return_add_type_to_dict(dct,self.__class__.__name__)
[docs]@classmethoddeffrom_dict(cls:type[_T],dictionary:dict)->_T:"""Create an object from its dictionary representation. Args: dictionary: The dictionary representation. Returns: The reconstructed object. """returnconverter.structure(dictionary,cls)
[docs]defto_json(self,sink:str|Path|SupportsWrite[str]|None=None,/,*,overwrite:bool=False,**kwargs:Any,)->str:"""Create an object's JSON representation. Args: sink: The JSON sink. Can be: - ``None`` (only returns the JSON string). - A file path or ``Path`` object pointing to a location where to write the JSON content. - A file-like object with a ``write()`` method. overwrite: Boolean flag indicating if to overwrite the file if it already exists. Only relevant if ``sink`` is a file path or ``Path`` object. **kwargs: Additional keyword arguments to pass to :func:`json.dumps`. Raises: FileExistsError: If ``sink`` points to an already existing file but ``overwrite`` is ``False``. Returns: The JSON representation as a string. """string=json.dumps(self.to_dict(),**kwargs)ifisinstance(sink,str):sink=Path(sink)ifisinstance(sink,Path):ifsink.is_file()andnotoverwrite:raiseFileExistsError(f"The file '{sink}' already exists. If you want to overwrite it, "f"explicitly set the 'overwrite' flag to 'True'.")sink.write_text(string)elifsinkisNone:passelse:sink.write(string)returnstring
[docs]@classmethoddeffrom_json(cls:type[_T],source:str|Path|SupportsRead[str],/)->_T:"""Create an object from its JSON representation. Args: source: The JSON source. Can be: - A string containing JSON content. - A file path or ``Path`` object pointing to a JSON file. - A file-like object with a ``read()`` method. Raises: ValueError: If ``source`` is not one of the allowed types. Returns: The reconstructed object. """ifisinstance(source,Path):string=source.read_text()elifisinstance(source,str):try:string=Path(source).read_text()exceptOSError:string=sourceelse:try:string=source.read()exceptException:raiseValueError("The method argument must be a string containing valid JSON, ""a string holding a file path to a JSON file / a corresponding ""'Path' object, or a file-like object with a 'read()' method.")returncls.from_dict(json.loads(string))