[Python] Decorators with arguments different from function

Discussão em 'Python' iniciado por Stack, Novembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    My admittedly rudimentary understanding of decorators is that they should add functionality without changing the function's syntax. But how does one handle the case when one wants a wrapper that uses arguments not processed by the main function.

    For instance, I have a bunch of functions that process text from a file. To avoid having to open or close the files I want to use a decorator that (1) imports the files, (2) passes the lines to the text handler and (3) saves the file.

    Assuming that lines contains the contents of the file file.abc, I came up with the following:

    def readwrite(func):
    def inner(*args, **kwargs):
    if 'file' not in kwargs.keys():
    print("Opening", args[0])
    lines = "lorem ipsum and all that" #Assume file returns this content.
    else:
    print("Reading", kwargs['file'])
    lines = 'lorem ipsum and all that'

    func(*args, **kwargs)
    print("Closing file")
    return
    return inner

    @readwrite
    def remove_lipsum(lines):
    print("Removing ipsum from ", lines)
    return

    remove_lipsum('file.abc')


    This returns:

    Opening file.abc
    Removing ipsum from file.abc
    Closing file


    The if-else comes because the file might be passed as a name or unnamed argument. The problem of course is that now I have the wrapper accepting an argument not in the function definition.

    What would be the correct way to go about it? Simply use nested loops instead of decorators?

    Continue reading...

Compartilhe esta Página