Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply decorators to lambdas?

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.

like image 966
Rafe Kettler Avatar asked Nov 08 '10 16:11

Rafe Kettler


People also ask

Can you decorate a lambda function?

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.

Are lambdas Pythonic?

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).

Are lambdas faster than functions Python?

Being anonymous, lambda functions can be easily passed without being assigned to a variable. Lambda functions are inline functions and thus execute comparatively faster.

Can lambdas return values?

The lambda function can take many arguments but can return only one expression.


2 Answers

f = anotherdecorator(lambda x: x * 2) 
like image 73
dan04 Avatar answered Oct 09 '22 08:10

dan04


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" )  
like image 38
M Juckes Avatar answered Oct 09 '22 07:10

M Juckes