The Python or Operator Shortcut

If statements are one of the most basic concepts used in all programming languages. Unfortunately they also make code ugly, unreadable, and sometimes even inefficient. Check out this google talk on if statements: http://www.youtube.com/watch?v=4F72VULWFvc
Using the or operator we can avoid ifs when checking for null values before assignment:
Traditional if:

if foo != None:
    x = foo
else:
    x = ‘some default value’

Using the or operator:

x = foo or ‘some default value’

Leave a comment

Your email address will not be published. Required fields are marked *