Why doesn’t this work?
lambda: print "x"
Is this not a single statement, or is it something else?
The documentation seems a little sparse on what is allowed in a lambda…
lambda‘s body has to be a single expression. In Python 2.x,
In : from __future__ import print_function In : f = lambda x: print(x) In : f("HI") HI
what you’ve written is equivalent to
def anon(): return print "x"
which also results in a SyntaxError, python doesn’t let you assign a value to print in 2.xx; in python3 you could say
and it would work because they’ve changed print to be a function instead of a statement.
In cases where I am using this for simple stubbing out I use this:
fn = lambda x: sys.stdout.write(str(x) + "\n")
which works perfectly.
The body of a lambda has to be an expression that returns a value.
None. Similarly, you can’t assign the result of
>>> x = print "hello" File "<stdin>", line 1 x = print "hello" ^ SyntaxError: invalid syntax
You also can’t put a variable assignment in a lambda, since assignments are statements:
>>> lambda y: (x = y) File "<stdin>", line 1 lambda y: (x = y) ^ SyntaxError: invalid syntax
You can do something like this.
Create a function to transform print statement into a function:
def printf(text): print text
And print it:
The body of a lambda has to be a single expression.
Here, you see an answer for your question.
With Python 3.x, print CAN work in a lambda, without changing the semantics of the lambda.
Used in a special way this is very handy for debugging.
I post this ‘late answer’, because it’s a practical trick that I often use.
Suppose your ‘uninstrumented’ lambda is:
Then your ‘instrumented’ lambda is:
lambda: (print (3), 4)