For review: PEP 308 - If-then-else expression

Andrew Dalke adalke at mindspring.com
Fri Feb 7 21:40:52 EST 2003


Me:
> But people will use ..if..else.. in very complex ways,

After some consideration, after email from Ian Bicking, I've decided that my
position was a bit too rushed.  I looked through a non-trivial chunk of the
uses of "?:" in the linux kernel and decided that that construct is not
often
misused.  That suggests my worries were overblown.

I still point out that:
  - the examples I gave can be written in the same number of lines
(and fewer characters) using existing Python constructs, like
       print ["imaginary", "duplicate", "real"][cmp(descr, 0.0)+1]

My scan of the linux source suggests that most uses of ?: are of this
sort, eg
      mode_wanted ? "en" : "dis"
could be written in Python as
    ["en", "dis"][mode_wanted]

and  *mount_opts |= f ? SF_SETUID : SF_SETGID
as    mount_opts |= [SF_SETGID, SF_SETUID][bool(f)]

and iov[1].iov_base = (param == NULL) ? padding : param
as   iov[1].iov_base = param or padding

and most uses of ?: are to prevent having to create a temporary
variable, and not to save evaluating both sides of the expression.

2. I still think it's easier for people to learn how the code flow
works with if/else statements because it's easy to stick in a
print statement on the different branches.

One other thing I came up with.  I'll often write

x = None
if s.find("spam"):
  x = "eggs?"

I do this because it guarantees that no matter what happens in the
if statement, the 'x' will be initialized.  That's handy in more complicated
if statements.  Also, it saves a line ;)

Take away the newlines and replace the ": x =" with "else"

x = None if s.find("spam") else "eggs?"

and the behaviour is exactly opposite.  I wonder how many
times people will make that mistake?

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list