Welcome, guest | Sign In | My Account | Store | Cart

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 line
1
decorator_with_args = lambda decorator: lambda *args, **kwargs: lambda func: decorator(func, *args, **kwargs)

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(): # ....

2 comments

arjun 12 years, 11 months ago  # | flag

Very interesting, but I AM having trouble wrapping my head around it.

Can you please include an example or use-case?

Ralph Bean 12 years, 9 months ago  # | flag

I wrote up an example that may be of help.

Created by Peter Hunt on Fri, 23 Dec 2005 (PSF)
Python recipes (4591)
Peter Hunt's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks