4

I would like my function to return 1, 2, or 3 values, in regard to the value of bret and cret. How to do something more clever than this ? :

def myfunc (a, bret=False, cret=False):
  b=0
  c=0
  if bret and cret:
   return a,b,c
  elif bret and not cret:
   return a,b
  elif not bret and cret:
   return a,c
  else:
   return a
Basj
  • 41,386
  • 99
  • 383
  • 673

6 Answers6

4

How about:

def myfunc(a, bret=False, cret=False):
   ...
   return (a,) + ((b,) if bret else ()) + ((c,) if cret else ())
NPE
  • 486,780
  • 108
  • 951
  • 1,012
3
def myfunc (a, bret=False, cret=False):
  b, c, ret = 0, 0, [a]
  if bret: ret.append(b)
  if cret: ret.append(c)
  return ret
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2
def myfunc(a, bret=False, cret=False):
    return [v for v, ret in [(a, True), (0, bret), (0, cret)] if ret]

Take a moment to read about Python List Comprehensions. They are handy very often!

Robert Kajic
  • 8,689
  • 4
  • 44
  • 43
1

You might simply append your return values to a list or use yield. You can iterate over the result afterwards and do what you please. Here's an explanation to the yield-Keyword: What does the "yield" keyword do in Python?

Community
  • 1
  • 1
TheWormKill
  • 23
  • 1
  • 6
1

You could return a list. Look:

def myfunc (a, bret=False, cret=False):

    list = []
    list.append(a)
    b=0
    c=0

    if bret:
        list.append(b)

    if cret:
        list.append(c)

    return list

Solve your question?

ddetoni
  • 33
  • 1
  • 7
  • no, the problem is not having a list. The problem is that this won't work anymore if 3 conditions, then there would be 2^3=8 cases to distinguish ! not beautiful ;) – Basj Dec 07 '13 at 13:50
  • This is equivalent to a much earlier solution posted by @thefourtheye (and I'd recommend against calling the variable `list` since this shadows the built-in function.) – NPE Dec 07 '13 at 14:27
1

Please note if you have to return tuple (in your question it returns tuple) use this -

def myfunc(a, bret=False, cret=False):
    return tuple([a] + [0 for i in (bret, cret) if i])
Arovit
  • 3,579
  • 5
  • 20
  • 24