Is there any syntax for using a decorator on a lambda function in Python? Example:
def simpledecorator(f): def new_f(): print "Using a decorator: " f() return new_f @simpledecorator def hello(): print "Hello world!"
Results in this output:
>>> hello() Using a simple decorator: Hello world!
Yet when I try the same with a lambda:
@anotherdecorator f = lambda x: x * 2
I get this:
File "<stdin", line 2 f = lambda x: x * 2 ^ SyntaxError: invalid syntax
I feel like this might be a good way to make lambdas more versatile by allowing statements to be "injected" into them. But if there exists such a feature, I don't know what the syntax is.
Actually, if you just want to decorate something very simple or two on functions, using this lambda decorator expression may not be a really bad idea. After all, you need to write at least 4–5 lines to implement a basic decorator otherwise.
Syntax. Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression).
Being anonymous, lambda functions can be easily passed without being assigned to a variable. Lambda functions are inline functions and thus execute comparatively faster.
The lambda function can take many arguments but can return only one expression.
f = anotherdecorator(lambda x: x * 2)
There appear to be two options which give the functionality, but without the clean syntax:
(1) Keep lambda
and ditch the decorator syntax (as posted by dan04):
f = simpledecorator( lambda : print( "Hello World" ) )
(2) Keep the decorator syntax and use a 1 line def
statement instead of lambda:
@simpledecorator def f(): print ( "Hello World" )
This 2nd form may be preferable if you want to chain decorators:
@simpledecorator @simpledecorator def f(): print ( "Hello World" )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With