Jess
Jess

Reputation: 429

How to get arguments to a decorator?

Is there a way to get the arguments to a decorator given the function being wrapped? For example,

@job('default')
def update_index():
    call_command("update_index", remove=True) 


func = update_index
args = ?? # How to use 'func' to get the string 'default' here?

Upvotes: 0

Views: 124

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

Generally speaking, you can't.

job('default') is executed first; what that returns is used as the decorator; in essence, python does:

def update_index():
    call_command("update_index", remove=True) 
update_index = job('default')(update_index)

As such, job('default') could return anything. It could return a function that does nothing but return it's argument:

def job(value):
    return lambda f: f

This does nothing with value, and the returned 'decorator' is a no-op, it returns the original function unchanged.

For specific decorators, it may well be that they leave behind a closure or extra attributes we could introspect. But that really depends on the specific decorator.

Upvotes: 4

Related Questions