Search code examples
pythonbooleanshort-circuiting

Catching a value of None with "or" in an expression


I came across this in a code review:

def some_method(self, path):
   path = os.path.abspath(os.path.expanduser(path or ""))

My first reaction was "ahhhh bad!" but on second thought... is it?


Solution

  • This is a common pattern for implementing some kind of a default value or fallback value if the first part of the expression evaluates to False. Consider it as best-practice - like it or not. It can also be used to turning None into an empty string.