Search code examples
pythondecoratorkeywordnamed-parameters

Named keywords in decorators?


I've been playing around in depth with attempting to write my own version of a memoizing decorator before I go looking at other people's code. It's more of an exercise in fun, honestly. However, in the course of playing around I've found I can't do something I want with decorators.

def addValue( func, val ):
    def add( x ):
        return func( x ) + val
    return add

@addValue( val=4 )
def computeSomething( x ):
    #function gets defined

If I want to do that I have to do this:

def addTwo( func ):
    return addValue( func, 2 )

@addTwo
def computeSomething( x ):
    #function gets defined

Why can't I use keyword arguments with decorators in this manner? What am I doing wrong and can you show me how I should be doing it?


Solution

  • You need to define a function that returns a decorator:

    def addValue(val):
        def decorator(func):
            def add(x):
                return func(x) + val
            return add
        return decorator
    

    When you write @addTwo, the value of addTwo is directly used as a decorator. However, when you write @addValue(4), first addValue(4) is evaluated by calling the addValue function. Then the result is used as a decorator.