var1, var2, var3 = (a or '---' for a in [var1, var2, var3])
Check if condition matches multiple variables
-
08-10-2022 - |
Question
I have a method/function that get's passed several variables that possibly have None value. How can I check all variables for None value and replace it with a string in the most pythonic way possible?
Example code:
def logData(self, var1=None, var2=None, var3=None):
if var1 is None:
var1 = "---"
if var2 is None:
var2 = "---"
if var3 is None:
var3 = "---"
# what I would prefer / pseudo code:
if list(var1, var2, var3) is None:
list[1] = "---"
Solution
OTHER TIPS
Use tuple unpacking:
var1, var2, var3 = ['---' if (x is None) else x for x in (var1, var2, var3)]
You could achieve this by using **kwargs
:
def logData(self, **kwargs):
for key,value in kwargs.iteritems():
if value is None:
# do assignment ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow