[Python] Where should I put my decorator definitions? [closed]

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    I have my class, but I wanted to log when functions are executed and whit which parameters, so I wrote my decorators.

    At moment I have everything in a single script, which looks more or less like:

    import...

    decorators...

    my class...


    I don't like the decorators hanging outside of my class, I have a function to initialize the log level and a function which is never used as decorator, but it is used by the other decorators.

    Should I put my decorators in a decorator.py file and import it in my class script? Should I leave them like that and learn to love this kind of file structure?

    def initialize_log(db):
    logzero.loglevel(logging.INFO)
    logzero.logfile("sw-" + db + ".log")


    def _log(log_function, f, *args, **kwargs):
    arguments = ""
    if len(args) > 1:
    arguments = " ({})".format(','.join(map(str, args[1:])))

    kwarguments = ""
    if len(kwargs) > 0:
    kwarguments = " ({})".format(','.join([str(k) + "=" + str(kwargs[k]) for k in kwargs]))

    log_function(f.__name__ + " started" + arguments + kwarguments)
    res = f(*args, **kwargs)
    log_function(f.__name__ + " completed" + arguments + kwarguments)
    return res


    def log_info(f):
    def _decorator(*args, **kwargs):
    return _log(logger.info, f, *args, **kwargs)

    return _decorator


    def log_debug(f):
    def _decorator(*args, **kwargs):
    return _log(logger.debug, f, *args, **kwargs)

    return _decorator

    Continue reading...

Compartilhe esta Página