Python equivalent for MySQL's IFNULL

If you want to convert all "falsy" values (i.e. None, 0, "", [], False, etc.) to a specific value and let everything else through untouched, you can use or. For example:

print (x or default_value)

will print the value of x if it's truthy, and the value of default_value if x is falsy.

I mention this because IFNULL is often used this way to clean up nulls in boolean and numerical columns in a database and so might be what you or others were after. Obviously, if you want to treat None differently to 0, False, etc. this won't work.


Not really, since you can't rebind arguments.

if foo is None:
  foo = 42

or

def ifnull(var, val):
  if var is None:
    return val
  return var

foo = ifnull(foo, 42)

Like this:

x = SOME_VALUE if x is None else x

Tags:

Python