lundi 6 juin 2022

Is the use of this decorator compatible with the design pattern?

I want to print the elapsed time of a method

class MyObject:
    def __init__(self, verbose):
        self._verbose = verbose

    def func(self):
        start = time.time()
        ...
        table = ...
        ...
        end = time.time()
        if self._verbose:
            print("the {} {}(s) in {:.3f}".format(len(table), table.name, end - start))

recently I discover design pattern and change this code to avoid repetitive complexity when printing elapsed time for multiple methods and function

TIME_LOGGER = None

class TimeLogger:
    def __init__(self, verbose=True):
        self._verbose = verbose
        self._format = []
    
    def __call__(self, text):
        def inner(func):
            def wrapper(*args, **kwargs):
                if self._verbose:
                    start = time.time()
                    result = func(*args, **kwargs)
                    end = time.time()

                    format = [(end - start) if f is TIME_LOGGER else f for f in self._format]
                    print(text.format(*format))
                    self.set_format([])

                    return result
                return func(*args, **kwargs)
            return wrapper
        return inner

    def set_format(self, format):
        self._format = format

class MyObject:
    def __init__(self, verbose):
        TIME_LOGGER(verbose)

    @TIME_LOGGER("the {} {}(s) in {:.3f}")
    def func(self):
        ...
        table = ...
        ...
        TIME_LOGGER.set_format([len(table), table.name, TIME_LOGGER])

getting a global var TIME_LOGGER sound anti-pattern

Aucun commentaire:

Enregistrer un commentaire