2

I'm trying to understand how this bit works:

Var_1, Var_2, Result =  some_function()

the script:

def some_function():
    return True, False, {"Some": "Dictionary"}

def main():
    Var_1, Var_2, Result =  some_function()
    if not Var_1:
        do something
    else:
        do something_else(Var_2, Result)

if __name__ == '__main__':
    main()

For me the difficult to grasp is the bit of doing inception and provide(return) values which will be used in the main function and in the same trigger the some_function() from within the main() function.

Since I'm new to advanced concepts in python, I found it really interesting. How this "operation" is called so I can read a bit more about how it works. i.e. returning some values in line order separated by , and interpreting them based on the position in line(for the lack of better description).

MMT
  • 1,931
  • 3
  • 19
  • 35

4 Answers4

5

It's returning a tuple. A tuple in Python is similar to a list, but it's immutable: you can't add, remove or replace items.

Often, tuples are constructed with the syntax (a, b, c), but the parentheses are optional in many cases, so a, b, c is also valid.

On the receiving end, tuple unpacking is used to get the individual elements of the tuple, and assign them to separate variables.

Thomas
  • 174,939
  • 50
  • 355
  • 478
3

What is happening here is in fact not that several values are returned. Instead, a single tuple is returned, and this is then unpacked using something called tuple unpacking.

The code is equivalent to

tmp_tuple = some_function()  # return tuple
Var_1, Var_2, Result = tmp_tuple  # unpack tuple
Jonas Adler
  • 10,365
  • 5
  • 46
  • 73
1

some_function() returns a tuple (True, False, {"Some": "Dictionary"}).

Tuples are very useful for grouping related data, for example something like ('John Smith', 1960, 'England', 'London', 'Newham') might be a better way to store information about a person then creating 5 separate variables.

When Var_1, Var_2, Result = tmp_tuple is called this tuple is unpacked:

 (Var_1, Var_2, Result) = (True, False, {"Some": "Dictionary"})

And hence:

Var_1 = True
Var_2 = False
Result = {"Some": "Dictionary"}
maestromusica
  • 706
  • 8
  • 23
0

The docs say:

Except when part of a list or set display, an expression list containing at least one comma yields a tuple

This means return x,y will return a single object - a tuple and the rest is just unpacking it to the separate values.

So i would say those are two operation: tuple creation in return statement and tuple unpacking in main.

K. Kirsz
  • 1,384
  • 10
  • 11