"""A file that containing the main implementation of the LightDB database management system"""importjsonfrompathlibimportPathfromtypingimportAny,Dict,TypeVar,Union,overload_T=TypeVar("_T")_VT=TypeVar("_VT")
[docs]classLightDB(dict):"""Light Database ~~~~~~~~~~~~~~ A lightweight database implemented as a dictionary with JSON file storage. This class extends the built-in Python `dict` class to provide a simple and easy-to-use key-value store that persists its data in a JSON file. The class provides methods to set, get, and remove individual key-value pairs. """_current_db:"LightDB"=Nonedef__init__(self,location:str)->None:"""Initialize the LightDB object Params: location (``str``): The path to the JSON file where the database is stored """super().__init__()self.location=Path(location)self.update(**self._load())LightDB._current_db=self
[docs]@classmethoddefcurrent(cls)->"LightDB":"""Returns the current instance of the LightDB class Returns: ``LightDB``: An initialized instance of the LightDB """ifcls._current_dbisNone:raiseValueError("No current database has been set")returncls._current_db
def__str__(self)->str:returnself.__repr__()def__repr__(self)->str:returnf"<LightDB: {self.location}>"def_load(self)->Dict[str,Any]:"""Load the database from a JSON file Returns: A dictionary containing the loaded key-value pairs """ifnotself.location.exists():return{}withself.location.open("r",encoding="utf-8")asfile:returnjson.load(file)
[docs]defsave(self)->None:"""Save the current state of the database to a JSON file"""withself.location.open("w",encoding="utf-8")asfile:json.dump(self,file,ensure_ascii=False,indent=4)
[docs]defset(self,key:str,value:Any)->None:"""Set a key-value pair in the database Params: key (``str``): The key to set value (``Any``): The value to associate with the key """self[key]=value
[docs]defget(self,key:str,default:Union[_VT,_T]=None)->Union[_VT,_T]:"""Get the value associated with a key from the database Params: key (``str``): The key to retrieve default (``Any``, optional): The default value to return if the key doesn`t exist Returns: ``_VT`` | ``_T``: The value associated with the key, or the default value if the key doesn`t exist """returnsuper().get(key,default)
[docs]defpop(self,key:str)->Any:"""Remove a key-value pair from the database Params: key (``str``): The key to remove Returns: ``Any``: The removed key-value pair """returnsuper().pop(key)
[docs]defreset(self)->None:"""Reset the database"""returnself.clear()