-1

I want to know how we get the value returned by a function - what the python return statement actually returns.

Considering following piece of code:

def foo():
    y = 5
    return y

When invoking foo(), we get the value 5.

x = foo()

x binds the integer object 5.

What does it mean? What does the return statement actually return here? The int object 5? Or variable name y? Or the binding to the object 5? Or something else?

How do we get the value returned by the return statement?

cs95
  • 379,657
  • 97
  • 704
  • 746
Bibek Ghimire
  • 522
  • 1
  • 4
  • 19
  • 4
    `y` is a reference to integer object `5`. `5` is also a reference to the integer object `5`. Everything is reference. – Jean-François Fabre Jul 24 '17 at 07:55
  • The `int` object 5 is returned – anon Jul 24 '17 at 07:56
  • This question seems to get used sometimes as a duplicate target for people who have a `return` statement inside a loop and want to return multiple values (although I can't understand why). That is a (completely and utterly) different problem; please see https://stackoverflow.com/questions/44564414/. – Karl Knechtel Dec 25 '22 at 00:36

2 Answers2

1

x binds the integer object 5.

Yes, x is a variable holding a reference to the integer object 5, which y also holds the reference to.

What does the return statement actually return here? The int object 5? Or variable name y? Or the binding to the object 5? Or something else?

To be precise, it is the reference to integer object 5 being returned. As an example, look at this:

In [1]: def foo():
   ...:     y = 5
   ...:     print(id(y))
   ...:     return y
   ...: 

In [2]: x = foo()
4297370816

In [3]: id(x)
Out[3]: 4297370816

How do we get the value returned by the return statement?

By accessing the reference that return passes back to the caller.

cs95
  • 379,657
  • 97
  • 704
  • 746
0

If you have any doubts you can always go to Python's REPL and experiment with values and functions. There is a type() instruction that can be used with values as well as with functions, for example:

Python 3.6.2 (default, Jul 19 2017, 13:09:21) 
[GCC 7.1.1 20170622 (Red Hat 7.1.1-3)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo():
...     y=5
...     return y
... 
>>> type(foo())
<class 'int'>

Regarding your foo() function, y is a local binding that holds the value int. return statement returns a value of variable y and this binding is not known outside the foo() function scope.

Szymon Stepniak
  • 40,216
  • 10
  • 104
  • 131