Python equivalent for MySQLs IFNULL

Python equivalent for MySQLs 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 its 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 wont work.

Not really, since you cant 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)

Python equivalent for MySQLs IFNULL

Like this:

x = SOME_VALUE if x is None else x

Leave a Reply

Your email address will not be published.