Steven D'Aprano steve+comp.lang.python at
Thu Oct 9 03:29:08 CEST 2014

Seymore4Head wrote:

> I want to toggle between color="Red" and color="Blue"
> Here is one:
>     if color == "Red":
>         color = "Blue"
>     else:
>         color = "Red"

Apart from the horrible spelling of colour :-) that seems fine to me. You
might wish to include a comment:

# Assumes that color can only take the values "Red" or "Blue".

just before the toggle code. But even better than a comment is an assertion:

assert color in ("Red", "Blue")
if color == "Red":
    color = "Blue"
    color = "Red"

This makes it a "checked comment" -- the primary purpose of the assert here
is as a comment, but the interpreter will by default actually check that it
is true (although that can be turned off by the user).

You can find out more about good, and bad, uses of assert here:

> Here is two:
> if x = "True" color = "Red"
> else:
> color="Blue"
> x= not x

That gives SyntaxError. And it's wrong because you are confusing the
*string* "T r u e" with the constant True. It should be:

assert isinstance(x, bool)
if x:  # don't write "if x == True" since that is redundant
    color = 'Red'
    color = 'Blue'
x = not x

> Others?

color = ("Red", "Blue")[color == "Red"]

color = {"Red": "Blue", "Blue": "Red"}[color]

color = "Red" if color == "Blue" else "Blue"

There may be even more complicated, obscure or obfuscated versions possible.


More information about the Python-list mailing list