(maint) code clean up (#187)
## bdfr - Add the bound instance as method parameter - Change methods not using its bound instance to staticmethods - Fix dangerous default argument - Refactor the comparison involving `not` - Refactor unnecessary `else` / `elif` when `if` block has a `raise` statement - Refactor unnecessary `else` / `elif` when `if` block has a `return` statement - Refactor useless `else` block in the loop - Remove implicit `object` from the base class - Remove reimported module - Remove unnecessary generator - Remove unnecessary return statement - Remove unnecessary use of comprehension - Remove unused imports - Use `is` to compare type of objects - Using not x can cause unwanted results ## Dockerfile - use a pinned Python version tag instead of latest - leverage cached requirements Signed-off-by: Vladislav Doster <mvdoster@gmail.com> Co-authored-by: Ali Parlakçı <parlakciali@gmail.com>
This commit is contained in:
@@ -3,6 +3,7 @@ from os import path, remove
|
||||
|
||||
from src.errors import InvalidJSONFile
|
||||
|
||||
|
||||
class JsonFile:
|
||||
""" Write and read JSON files
|
||||
|
||||
@@ -10,13 +11,13 @@ class JsonFile:
|
||||
|
||||
Use delete(self,*deletedKeys) to delete keys
|
||||
"""
|
||||
|
||||
|
||||
FILEDIR = ""
|
||||
|
||||
def __init__(self,FILEDIR):
|
||||
def __init__(self, FILEDIR):
|
||||
self.FILEDIR = FILEDIR
|
||||
if not path.exists(self.FILEDIR):
|
||||
self.__writeToFile({},create=True)
|
||||
self.__writeToFile({}, create=True)
|
||||
|
||||
def read(self):
|
||||
try:
|
||||
@@ -25,19 +26,21 @@ class JsonFile:
|
||||
except json.decoder.JSONDecodeError:
|
||||
raise InvalidJSONFile(f"{self.FILEDIR} cannot be read")
|
||||
|
||||
def add(self,toBeAdded,sub=None):
|
||||
def add(self, toBeAdded, sub=None):
|
||||
"""Takes a dictionary and merges it with json file.
|
||||
It uses new key's value if a key already exists.
|
||||
Returns the new content as a dictionary.
|
||||
"""
|
||||
|
||||
data = self.read()
|
||||
if sub: data[sub] = {**data[sub], **toBeAdded}
|
||||
else: data = {**data, **toBeAdded}
|
||||
if sub:
|
||||
data[sub] = {**data[sub], **toBeAdded}
|
||||
else:
|
||||
data = {**data, **toBeAdded}
|
||||
self.__writeToFile(data)
|
||||
return self.read()
|
||||
|
||||
def delete(self,*deleteKeys):
|
||||
def delete(self, *deleteKeys):
|
||||
"""Delete given keys from JSON file.
|
||||
Returns the new content as a dictionary.
|
||||
"""
|
||||
@@ -51,8 +54,8 @@ class JsonFile:
|
||||
return False
|
||||
self.__writeToFile(data)
|
||||
|
||||
def __writeToFile(self,content,create=False):
|
||||
def __writeToFile(self, content, create=False):
|
||||
if not create:
|
||||
remove(self.FILEDIR)
|
||||
with open(self.FILEDIR, 'w') as f:
|
||||
json.dump(content, f, indent=4)
|
||||
json.dump(content, f, indent=4)
|
||||
|
||||
Reference in New Issue
Block a user