Added an indentation parameter.

This commit is contained in:
The Wobbler 2024-12-07 22:43:35 +01:00
parent c50525b561
commit d88f4964fe

View file

@ -4,7 +4,6 @@
Using this module, you can store data in files easily.
"""
import os
import json
from deprecated import deprecated
@ -66,53 +65,6 @@ class DictFile:
return len(self.settings)
class DataclassJSONFile:
"""
Store a dataclass in a JSON file.
"""
def __init__(self, file_path, dataclass, class_instance=None):
self.file_path = file_path
self.dataclass = dataclass
self.class_instance = class_instance
if class_instance is None: # load the class instance from the file if it is None
self.load_from_file(file_path)
def load_from_file(self, file_path):
file = open(file_path, "r")
class_dict = json.load(file)
file.close()
self.class_instance = self.dataclass(**class_dict)
def save_to_file(self):
class_dict = self.class_instance.__dict__
file = open(self.file_path, "w")
json.dump(class_dict, file)
file.close()
def __repr__(self):
return repr(self.class_instance)
def __getitem__(self, key):
return getattr(self.class_instance, key)
def __setitem__(self, key, value):
setattr(self.class_instance, key, value)
def __delitem__(self, key):
delattr(self.class_instance, key)
def __iter__(self):
return self.class_instance.__iter__()
def __len__(self):
return len(self.class_instance.__dict__)
# these 2 functions do the exact same thing as the functions in the class above
def load_dataclass_json(dataclass, file_path: str, builtin_save: bool=True):
"""
Loads a dataclass instance from a json file.
@ -122,7 +74,8 @@ def load_dataclass_json(dataclass, file_path: str, builtin_save: bool=True):
:param bool builtin_save: If True, you can simply call instance.save(file_path) to store the data.
:return: An instance of the dataclass containing the data from the json file.
"""
if os.path.exists(file_path):
if os.path.exists(file_path): # initialize instance with default values if the file doesn't exist
file = open(file_path, "r")
class_dict = json.load(file)
file.close()
@ -132,22 +85,23 @@ def load_dataclass_json(dataclass, file_path: str, builtin_save: bool=True):
instance = dataclass(**class_dict)
if builtin_save:
if builtin_save: # add save method so that we can easily do "instance.save()"
dataclass.save = save_dataclass_json
return instance
def save_dataclass_json(class_instance, file_path: str):
def save_dataclass_json(class_instance, file_path: str, indent: None | int | str=2):
"""
Saves a dataclass instance to a json file.
:param class_instance: The instance of the dataclass to be saved.
:param str file_path: The path to the file in which the data gets written.
:param None|int|str indent: The indentation level for cleaner output.
"""
class_dict = class_instance.__dict__
class_dict = dict(filter(lambda pair: not callable(pair[1]), class_dict.items())) # filter out functions
file = open(file_path, "w")
json.dump(class_dict, file)
json.dump(class_dict, file, indent=indent)
file.close()