[Tutor] lambda: print('x') raises SyntaxError?
wesley chun
wescpy at gmail.com
Thu Jul 5 18:36:27 CEST 2007
On 7/5/07, Kent Johnson <kent37 at tds.net> wrote:
> 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 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.
one thing to keep in mind when thinking, "is this an expression or a
statement?" is that the former will always evaluate to some sort of
Python object (numerical calculation, function return value [your case
above], some string you've built, etc.) whereas the latter will not
have any kind of intrisic value (print, while, if, class, def... none
of these have a "value").
on a partially-related note, print will be changing to a function in
the next generation of Python... see PEP 3105:
http://www.python.org/dev/peps/pep-3105/
for a list of some of the other changes coming down the line:
http://www.python.org/dev/peps/pep-3100/
cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com
wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
More information about the Tutor
mailing list