lundi 27 mars 2023

Dynamic Inheritance, some piece of code... could you look and help mi in improving my code?

So i built this piece of code, but it looks like something is wrong in it. Is it not bad practice to creates function which creates class like belowe?

Should i build some subclasses?

base file

class BaseCsvLogger(ABC):
    """The file name is the same for whole working app time.
    """
    # some code ...
    def log_to_file(self, *args):
        ...

class DynamicFileName:
    @property
    def filename(self):
        return self.__filename()

class StaticFileName:
    @property
    def filename(self):
        return self.__filename

DynamiclyOpenFile class has modified log_to_file function to open file just befor super().log_to_file and close it just after.
StatyclyOpened open file in init method.

final class creator

from base_logger import DynamicFileName, StaticFilename, BaseCsvLogger


def Logger(filename: Union[str, Callable[[], str]],
           headers: Iterable[str],
           datetime_fmt: str,
           sep: str = ';',
           dec: str = ',',
           open_on_logging: bool = False) -> BaseCsvLogger:

    if open_on_logging:
        baseclass = DynamiclyOpenFile
    else:
        baseclass = StaticlyOpened

    if callable(filename):
        fname_type = DynamicFileName
    else:
        fname_type = StaticFilename

    class LoggerTmp(baseclass, fname_type):
        def __init__(self,
                     filename,
                     headers,
                     datetime_fmt,
                     sep,
                     dec) -> None:
            super().__init__(filename,
                             headers,
                             datetime_fmt,
                             sep, dec)
    logger = LoggerTmp(filename, headers, datetime_fmt, sep, dec)
    return logger

Aucun commentaire:

Enregistrer un commentaire