🏃♀

How Python Executes a Function Call

Running through what Python does!
There's two stages at which Python interacts with a function — when it first finds and creates the function, and when the function is called. In this chapter, we'll go over what Python does behind the scenes in each of these stages.

Creating the Function

Consider the following function, which accepts two value, prints one, and returns the double of that other.
def f(x, y):
print(y)
return 2 * x
When Python first sees this definition, it adds a function f to the list of functions that can be called in the program, and it remembers that this function f accepts two argument, but it does not read the inside of the function. Everything that is tabbed is ignored by Python. To see this, consider another function that should error:
def f():
return 1/0
However, if this function is never called, it will never error.

Calling the Function

Now that the function is created, we should go ahead and call it!
a = 7
def f(x, y):
print(y)
return 2 * x
​
f(a, 4 + 5 * 2)
What is Python doing when it first sees the function call on Line 6? First, it goes looking for the function f — and throws an error if it doesn't find it. Try changing line 6 to read something like g(a) to see Python get mad.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'g' is not defined
Next, it evaluates all the arguments that are passed into the function call. It evaluates a to be equal to 7 and evaluates 4+5*2 to be equal to 14. Once these are evaluated, Python checks if the number of arguments given to the function — and errors if the numbers do not match the number of inputs the function accepts.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() takes 2 positional arguments but 1 was given
If all these checks pass, congratulations! The function call is made. If there are any errors in the code within the function, this is where they will get mad.
The inputs are set to the values passed in — x=7 and y=14 here. The code within the function in executed to completion — we print 14 and return 7*2 = 14.
Python executes a function until the first return statement that it finds.