ActiveState Code

Recipe 465427: Simple decorator with arguments


Many Python programmers have trouble wrapping their mind around decorators that accept arguments. Here's a one-line decorator designed just for making decorators that accept arguments.

Python
1
decorator_with_args = lambda decorator: lambda *args, **kwargs: lambda func: decorator(func, *args, **kwargs)

Discussion

A lot of people have trouble wrapping their mind around closures and decorators. Instead of writing a closure, with this code you can now write decorators that take the decorated function as the first argument and all arguments passed to the decorator as subsequent arguments:

@decorator_with_args def mydecorator(func, myarg): # ... do something with func and myarg ... return func

which can be called like this

@mydecorator(myarg="...") def myfunc(): # ....

Sign in to comment