Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent for MySQL's IFNULL

Tags:

python

Is there a function in Python that checks if the returned value is None and if it is, allows you to set it to another value like the IFNULL function in MySQL?

like image 781
super9 Avatar asked May 13 '11 04:05

super9


Video Answer


1 Answers

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.

like image 153
voracity Avatar answered Sep 28 '22 11:09

voracity