[Tutor] lambda: print('x') raises SyntaxError?

Kent Johnson kent37 at tds.net
Thu Jul 5 17:34:59 CEST 2007


wc yeee wrote:
> Hi. Is there a reason the code below raises a syntax error? It's 
> probably something silly on my part, but I can't figure it out:
> 
> 
>  >>> b = lambda: print('bar')
>   File "<stdin>", line 1
>     b = lambda: print('bar')
>                              ^
> SyntaxError: invalid syntax

The body of a lambda has to be an expression, not a statement. print is 
a statement.
> 
> 
> This code seems to work fine, so I don't know why the "print" statement 
> in the above code is wrong.

Don't know how it can work fine if it won't compile; what's your secret? ;-)


> This works fine too:
> 
>  >>> import sys
>  >>> a = lambda: sys.stdout.write('foo\n')
>  >>> a()
> foo

Right, that is an expression and it is the workaround for your original 
problem.

Kent


More information about the Tutor mailing list