Search code examples
pythondiscordpython-decoratorspycord

Is it possible to pass a function argument into a decorator?


def my_decorator(func):

    def inner():
        """do stuff with arg"""
        func()

        return func

    return inner

@my_decorator
def my_func(arg):
    pass

I wish to make the argument passed to the function my_function() to be passed to the decorator my_decorator(). I know it is possible to pass a variable to the decorator by putting it in a call like this: @my_decorator("arg"), but I am using the pycord library, which passes arguments directly to the function.

Is there any way to do it in Python, or will I have to find another way?

I could put this code in the function itself, but if the code is expanded later, it could cause problems, and it's way easier to maintain and update a single decorator/wrapper than change multiple places in code.


Solution

  • Yes – your def inner(): should be def inner(arg):; after all, the function you return from the decorator effectively replaces the original function.

    def my_decorator(func):
        def inner(arg):
            print(f"Going to increase {arg} by 1 before passing it to func!")
            return func(arg + 1)
        return inner
    
    @my_decorator
    def my_func(arg):
        print(f"my_func: {arg}")
    
    my_func(9)
    

    prints out

    Going to increase 9 by 1 before passing it to func!
    my_func: 10