开发者

Python equivalent for MySQL's IFNULL

开发者 https://www.devze.com 2023-03-05 08:28 出处:网络
Is there a function in Python that checks i开发者_开发知识库f the returned value is None and if it is, allows you to set it to another value like the IFNULL function in MySQL? If you want to convert a

Is there a function in Python that checks i开发者_开发知识库f the returned value is None and if it is, allows you to set it to another value like the IFNULL function in MySQL?


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


nvl(v1,v2) will return v1 if not null otherwise it returns v2.

nvl = lambda a,b: a or b


From MySQL:

nvl(foo, bar) [or even nvl2(foo, baz, bar) in Oracle]

Using Python ternary operator (see detailed explaination here) within a lambda function as follows:

nvl = lambda foo, bar: bar if foo is None else foo

nvl2 = lambda foo, baz, bar: bar if foo is None else baz


foo = nvl(foo, 42) # returns 42 if foo is null

foo = nvl2(foo, 7, 42) # returns 42 if foo is null or 7 is foo is not null


We made this one:

def d_nvl(d,key,default_val):
    try:
        return d[key]
    except Exception:
        return default_val

and it is used this way: my_val = d_nvl(my_dict,'my_key','default_val')


I'm using SQL Oracle, it has NVL() function which replaces null. For example, NVL(null,1) returns 1 and NVL(3,1) returns 3. Simple python equivalent for that function:

import numpy as np

nvl = lambda a,b: b if np.isnan(a) else a

nvl(3,1)
>>> 3
nvl(np.nan,1)
>>> 1


Since this question is now over 2 years old I guess this is more for future references :)

What I like to do is max('', mightBeNoneVar) or max(0, mightBeNoneVar) (depending on the context).

More elaborate example:
print max('', col1).ljust(width1) + ' ==> '+ max('', col2).ljust(width2)

0

精彩评论

暂无评论...
验证码 换一张
取 消