- Learn Web Development with Python
- Fabrizio Romano Gaston C. Hillar Arun Ravindran
- 314字
- 2021-06-10 18:26:11
Argument-passing
Take a look at the following code. We declare a name, x, in the global scope, then we declare a function, func(y), and finally we call it, passing x:
# key.points.argument.passing.py
x = 3
def func(y):
print(y)
func(x) # prints: 3
When func is called with x, within its local scope, a name, y, is created, and it's pointed to the same object x is pointing to. This is better clarified by the following figure (don't worry about Python 3.3, this is a feature that hasn't changed):

The right part of the preceding figure depicts the state of the program when execution has reached the end, after func has returned (None). Take a look at the Frames column, and note that we have two names, x and func, in the global namespace (Global frame), pointing to an int (with a value of 3) and to a function object, respectively. Right beneath it, in the rectangle titled func, we can see the function's local namespace, in which only one name has been defined: y. Because we have called func with x (line 5 in the left part of the figure), y is pointing to the same object that x is pointing to. This is what happens under the hood when an argument is passed to a function. If we had used the name x instead of y in the function definition, things would have been exactly the same (only maybe a bit confusing at first), there would be a local x in the function, and a global x outside, as we saw in the Scopes and name resolution section previously in this chapter.
So, in a nutshell, what really happens is that the function creates, in its local scope, the names defined as arguments and, when we call it, we basically tell Python which objects those names must be pointed toward.