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

Tim Peters tim.one at comcast.net
Sat Feb 8 14:33:07 EST 2003


[Andrew Dalke]
> ...
> 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?

Fewer than make the other mistake here <wink -- but I make it too>:  .find
returns an index, not a bool, so the original leaves x at None if s begins
with "spam" (in which case s.find("spam") returns 0, so is false), and sets
x to "eggs?" if spam doesn't appear in s at all (in which case
s.find("spam") returns -1, so is true) or if spam does appear in s but not
starting at index 0.

BTW, that's one of the motivations for 2.3 liberalizing "in" with string
operands, so that you'll be able to write

    x = None
    if "spam" in s:
        x = "eggs?"

instead and actually have it work as intended.






More information about the Python-list mailing list