Tag : else

One line if statements in Python

Every once in a while it is kind of nice to put a one-liner if statement in a Python program.  I don’t use these very often as they can make the code harder to read.  However I do think they have their place.  Mainly I use these when I need set the value of a variable based on a condition.  So lets say I start with a variable called dummy, and set it to None.

[python]

dummy = None

[/python]

And I want to set dummy to something, but only if dummy is still none, so:

[python]

dummy = (something if dummy is None else dummy)

[/python]

This is the same as writing:

[python]
if dummy is None:
dummy = something
else:
dummy = dummy
[/python]

The one line expression is a much simpler way to express this condition.