0

Does anybody have an idea, how to check the value of a variable a == 0 from an multiple return value function in a single IF statement like below,

if (a, b, c = some_function()) == 0: #currently it is wrong
    ...
    ...
else:
    ...
    ...

def some_function():
    return 0, 123, "hello"

2 Answers2

1

First unpack the return values to variables, then check the value of the variable.

You can use _ as variable name to indicate that the value is not used.

a, _, _ = some_function()
if a == 0:
    # ...

Or if you don't need to access any of the return values later at all, you can use indexing:

if some_function()[0] == 0:
    # ...

But that is less readable, because you don't get to give a name to the return values to document their meaning.

It would be tempting to use the "walrus operator" :=, but it does not support iterable unpacking (which is used in the first example).

mkrieger1
  • 10,793
  • 4
  • 39
  • 47
  • Thanks @mkrieger1 it worked out for me. But I need to call the function again within IF to get the return values but I can live with that. – Ameen Abbas Sep 17 '20 at 10:23
0

This is the closest I was able to get with the walrus operator. My apologies for closing the ticket without checking completely enough.

def some_function():
    return 0, 123, "hello"

if (my_tuple := some_function() )[0] == 0:
    print ("Check worked")
else:
    print ("Check failed")

a, b, c = my_tuple

This is very close to mkrieger1's answer (upvoted), adding only a demonstration of receiving a single return value in the "walrus" assignment.

Prune
  • 72,213
  • 14
  • 48
  • 72
  • As much as I wanted to use this solution but I can't as I'm using Python 3.7 and I see walrus works only from 3.8. For now mkrieger1's solution has worked out for me. Ofcourse need to call the same function again within IF to get the return values though but it works. – Ameen Abbas Sep 17 '20 at 10:15