7

What is the preferred way to ignore an optional return values of function f()?

a)

foo, _ = f()

b)

foo = f()[0]

c)

def f(return_bar=True):
    if return_bar:
        return foo, bar
    else:
        return foo

foo = f(return_bar=False)
Amir
  • 10,600
  • 9
  • 48
  • 75
Max
  • 183
  • 1
  • 1
  • 6
  • definetly not `C`, `A` is more pythonic – Netwave May 18 '17 at 10:15
  • 2
    b) makes sense the most. c) is not scalable and a) just wastes space on a useless object. – Haris May 18 '17 at 10:15
  • a) is good if you want to skip value in the middle, like for *path, _, files in os.walk(...)* – volcano May 18 '17 at 10:18
  • @Haris what do you mean by scalable in this context? – Max May 18 '17 at 10:23
  • @Max, this cannot be a standard way of doing this because one cannot use this fro cases where a function can return 1, 2 or 3 return values. – Haris May 18 '17 at 10:25
  • @Haris this was actually exactly the case I had in mind. I thought `a, c = f(return_b=False, return_c=True, return_d=False)` might be nicer than `a, _, c, _ = f()` – Max May 18 '17 at 10:30
  • @Max. I don't think so. unnecessary check and parameter handling is needed. Definitely a) or b) is better. – Haris May 18 '17 at 10:35
  • c) is how `numpy.unique` does it – A. Donda Jan 14 '21 at 21:29
  • Does this answer your question? [Ignore python multiple return value](https://stackoverflow.com/questions/431866/ignore-python-multiple-return-value) – Josh Correia Feb 03 '21 at 19:43

1 Answers1

5

You're setting yourself up for trouble if your function returns two variables sometimes and one variable another time.

foo, _ = f()

Usually using underscore to ignore variables is the standard practice, but in your case, if for whatever reason, this call to f() returned only one variable, you will get a runtime error.

Unless you can guarantee that f() will return two variables this time, it's better to do this

b = f()

if(isinstance(b, tuple)):
    foo = b[0]
Amir
  • 10,600
  • 9
  • 48
  • 75
ハセン
  • 377
  • 3
  • 5