Writing one-liners in Python (was: Re: [Tutor] help mee)

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 1 May 2002 19:24:58 -0700 (PDT)


Hi Roger,


> 	Unfortunately, I have the impression that writing one-liners
> 	in Python isn't as easy as writing one-liners in Perl (for me
> 	at least -- I am still a newbie in Python).


Python's design puts constraints on one-liners, and I think it
intentionally discourages people from doing one-liners.  As an example of
such a constraint, we can look at Python's assignment operation:

###
a = b                   ## Assignment
###


Assignment in Python is done using a "statement".  What distinguishes a
statement from the other kind of command that Python allows, the
"expression", is that a statement can't be placed "within" another
expression:

###
(a = b) == None         ## <--- Does not work in Python
###

while an expression (like a boolean test or the result of a function call)
can be imbedded within another expression:

###
someFunctionCall((a == b) or (c < d) and not e,
                 f)
###


So Python really tries to make statements like assignment stand alone in a
line.  This is in contrast with a lot of other languages like C or Perl,
which treat assignment as an expression.  Personally, I don't think this
is a "bad" thing, just because assignment can be a scary thing, and it's
often good to have it stand out in a program.



>       The reason for my impression is that there aren't block
>	delimiters like C's or Perl's "{" and "}" available in Python.

Very true: that's another constraint that narrows down the space for
writing one liners.  This is not to say it's not possible in Python: it's
just that they're very hard to write and limited in what they can do...
or maybe not!

    http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.015.htp


I dunno, I feel a little sick when I see something like this.  *grin*




> 	As a result, I don't know how one would convert to a
> 	one-liner, say, something along the lines of the following
> 	code:
>
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> 	while (cond1 and cond2):
> 	    # do something
>
> 	# now, which condition failed? cond1 or cond2?
> 	if (cond1):
> 	    # cond2 failed and cond2 didn't
>         else:
>             # cond1 failed


To tell the truth, neither do I.  I'm not seeing an immediate way to do
this in one line in any language without severely sacrificing readability.
FAQ entry 4.15 above showed how evil some of those nested expressions can
get, so it might be possible, but may not be edifiable.  Or is that
editable?


Good luck to you!