1

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] = "---"
DominicM
  • 6,520
  • 13
  • 39
  • 60

3 Answers3

2

Use tuple unpacking:

var1, var2, var3 = ['---' if (x is None) else x for x in (var1, var2, var3)]
superjump
  • 151
  • 4
  • Seems complicated to me, can you explain a bit more? – DominicM Feb 08 '14 at 01:40
  • @DominicM Here's a simple example of tuple unpacking: # set var1 to 1, var2 to 2 and var3 to 3 var1, var2, var3 = 1, 2, 3 # now imagine that your function is called with parameters # var1 == 0, var2 == None and var3 = 5, the list comprehension # below: – superjump Feb 08 '14 at 12:30
  • @DominicM. Whoops, haven't got the hang of commenting yet. What I was trying to say was that, the list comp in the answer iterates through the values passed to your function, (var1, var2, var3), and if any of them are `None` replaces them with '---', otherwise they are left unchanged. Further, the list comp evaluates to three values which are assigned sequentially to variable names on the left, in this case var1, var2, var3. – superjump Feb 08 '14 at 12:43
  • Editing the answer might be more appropriate when adding more info to the answer. – DominicM Feb 09 '14 at 03:33
2
var1, var2, var3 = (a or '---' for a in [var1, var2, var3])
ndpu
  • 22,225
  • 6
  • 54
  • 69
  • @markrages this check is usually added when vars are mutabe, i think for integer it is not needed... but yes, this way im cant handle 0, condition should be changed to something like in superjump answer – ndpu Feb 07 '14 at 22:06
  • I am new to this method, can you explain exactly what each step does? – DominicM Feb 08 '14 at 01:41
  • @DominicM meaning of `a or '---'`: http://stackoverflow.com/questions/2580136/does-python-support-short-circuiting. Remains is tuple unpacking and list comprehension – ndpu Feb 08 '14 at 10:50
-1

You could achieve this by using **kwargs:

def logData(self, **kwargs):
  for key,value in kwargs.iteritems():
    if value is None:
      # do assignment ...
kinkee
  • 368
  • 2
  • 12