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.
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(): # ....
Very interesting, but I AM having trouble wrapping my head around it.
Can you please include an example or use-case?
I wrote up an example that may be of help.