Hi,
(I am re-posting here a post I made in 2019 on my blog)
A quick view on business and administrative logic separation.
A dummy example where we use decorators to check if the input path exists before assigning it to the class attribute. Context managers could accomplish the same, but with the decorator, checking takes place before even executing the function.
def check_folder_exists(func):
"""
Decorator for class property setters
"""
@wraps(func)
def wrapper(self, folder):
if not Path(folder).exists():
raise FileNotFoundError(f'Path not found: {folder}')
else:
return func(self, folder)
return wrapper
class Parameters:
def __init__(self, **kwargs):
self.kwargs = kwargs
@property
def db_folder(self):
return self._db_folder
@db_folder.setter
@check_folder_exists
def db_folder(self, folder):
self._db_folder = folder
Below is another snippet from my code where I use a combination of three contexts to handle exceptions hierarchically.
for step in config_reader.steps:
with GCTXT.abort_if_exception(), \
GCTXT.query_upon_error(XCPTNS.ConfigReadingException), \
GCTXT.abort_if_critical_exceptions(CONFREADER.critical_errors):
step()
Do you find this useful for your projects? Let me know.
Cheers,
Top comments (0)