a = b = 1 just syntactic sugar?

Michael Chermside mcherm at mcherm.com
Thu Jun 5 20:51:03 CEST 2003


Ed Avis writes:
> It seems a bit perverse that setattr is allowed in lambda expressions
> but assignment is not; that you can call setdefault to update a
> dictionary, but not simply set the dictionary's elements; that you can
> do sys.stdout.write but not print; that you can call a function which
> asserts but not call assert.
> 
> If lambda accepted statements as well as expressions - or if a
> statement could be used as an expression, as in C - then these warts
> would not arise.

True, but as usual, there's a reason for it. Lambda was intended[1] for
one purpose and one purpose only... to permit simple anonymous functions
to be used in places where the succinctness makes it more readable than 
using def to make a named function. Such places are rare except when
using functional style programming, where they are quite common. But
in functional style programming you (nearly always) do NOT want 
expressions to have side effects.

So lambda is defined to allow only expressions, and is *intended* for
simple, side-effect-free functions. While there's nothing *preventing*
you from calling a function with side effects, the prohibition on
using statements tends to discourage it. Good style is encouraged,
but you can violate the rules if you really want to (and know what
you're doing). If you want more, use def, and give it a name.

[1] This is only my own opinion of how and why Lamda works the way it
  does. In particular, Guido would disagree. He would say that lambda
  was included to satisfy the requests from lisp refugees, and that
  if he had it to do over he wouldn't just choose a better keyword,
  he'd prohibit the whole thing and require def everywhere. On this
  point I respectfully disagree with him... I find lambda to be quite
  nice, but ONLY when used for very small side-effect-free functions.
  And if I had a complaint, it wouldn't be about the (rarely needed
  and easily worked-around) prohibition on assignment statements,
  but about the (frequently needed and impossible to work around) lack
  of a conditional expression.

But-we-won't-bug-Guido-about-the-results-of-that-vote-until-after-2.3 lly,

-- Michael Chermside






More information about the Python-list mailing list