"""Misc utility classes and functions. ====================================== """ import os from salessheets.constants import pdf class DotDict(dict): """A wrapper around dict to access its items using dot notation.""" def __getattr__(self, item): """Get item from dictionary by it's key, using dot-notation. Args: item (str): key Returns: value, or None if there is no item with such key """ return self.get(item) def __setattr__(self, key, value): """Set value in dictionary, using dot-notation. Args: key (str): item key value: item value """ self[key] = value class EmptyDateException(Exception): """Raise when date field is empty.""" def __init__(self, arg): """Initiate exception with message.""" self.message = arg def datetime_to_str(date, date_format=pdf.REDESSENT_DATETIME_FORMAT): """Convert datetime object to string. Args: date (datetime object) date_format (str): string for date formatting. Returns: str: date string """ try: date_string = date.strftime(date_format) return date_string except AttributeError: raise EmptyDateException('Date should be the datetime object!') def remove_file(path): """Remove a file, and silently return if it doesn't exist. Args: path (str): path to file """ try: os.remove(path) except FileNotFoundError: pass def split_text_in_paragraphs(text_str): r"""Split string into paragraphs by \r\n. Args: text_str (str): text to split Returns: list: list of paragraphs """ return text_str.splitlines() if text_str else [] def cleanup_dict(dictionary): """Cleanup dictionary. Change None from dict elements to empty string, substitute values containing only spaces by empty string. Args: dictionary (dict): dictionary that should be cleaned from None. Returns: dict: cleaned dictionary. """ for key, value in dictionary.items(): # strings if isinstance(dictionary[key], str): dictionary[key] = dictionary[key].strip() # None elif dictionary[key] is None: dictionary[key] = '' return dictionary