Some syntactic sugar proposals

Mark Wooding mdw at distorted.org.uk
Thu Nov 18 20:53:13 EST 2010


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:

> >> Not everything needs to be a one liner. If you need this, do it the
> >> old- fashioned way:
> >>
> >> t = foo()
> >> if not pred(t): t = default_value
> > 
> > I already explained how to write it as a one-liner:
> > 
> >         t = (lambda y: y if pred(y) else default_value)(foo())
>
> I didn't say it couldn't be written as a one-liner. I suggested that it 
> was better not to.

Ahh.  I misunderstood the first sentence above as dismissing the
possibility.  Sorry.  I agree that it's not a /nice/ one-liner. ;-)

> The costs of the one-liner are:
>
> * reduced readability;
> * requires an increased level of knowledge of the reader ("what's lambda 
> do?");
> * runtime inefficiency (you create a function object, only to use it once 
> then throw it away).

This last can be obviated by a clever compiler (which, in our case, we
have not got).  The second could be considered an advantage: it's
educational!

> The advantages?
>
> * one fewer line of code.
>
> In my experience, the obsessiveness in which some people look for one-
> liners is far from helpful, and goes against the spirit of Python. This 
> isn't Perl :)

Oh, I agree completely.  On the other hand, it's just /fun/.  Python is
a fun language and using its features in playfully unusual ways is
enjoyable; like a good pun in a natural language.  Just as puns aren't
always appropriate in written language, playful code isn't always
appropriate either; but that doesn't mean it's never appropriate.

(Java has no sense of humour.  C++ does have, but it's a bit weird.)

-- [mdw]



More information about the Python-list mailing list