Reputation: 6888
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] = "---"
Upvotes: 1
Views: 690
Reputation: 151
Use tuple unpacking:
var1, var2, var3 = ['---' if (x is None) else x for x in (var1, var2, var3)]
Upvotes: 2
Reputation: 368
You could achieve this by using **kwargs
:
def logData(self, **kwargs):
for key,value in kwargs.iteritems():
if value is None:
# do assignment ...
Upvotes: -1