Search code examples
pythonpython-decorators

Decorator with arg that returns the same function as passed


I want a decorator that adds is parameter as an attribute to the underlying function, then returns that function itself. When I look in the module the function foo has been removed. it does not even show up.

def addarg(x):
    def decorator(func):
        func.x = x
        return func

@addarg(17)
def foo():
    pass

print(foo.x)    # should print 17

Solution

  • Based on @Karl's comment, your code requires a single line to be added -

    def addarg(x):
        def decorator(func):
            func.x = x
            return func
        return decorator # <-- Add this line
    
    @addarg(17)
    def foo():
        pass
    
    print(foo.x)
    

    That's all folks!