Tracing Function Calls in the Memory Model

Read the following code. Can you predict what it will do when we run it?

 >>>​​ ​​def​​ ​​f(x):
 ...​​ ​​x​​ ​​=​​ ​​2​​ ​​*​​ ​​x
 ...​​ ​​return​​ ​​x
 ...
 >>>​​ ​​x​​ ​​=​​ ​​1
 >>>​​ ​​x​​ ​​=​​ ​​f(x​​ ​​+​​ ​​1)​​ ​​+​​ ​​f(x​​ ​​+​​ ​​2)

That code is confusing, in large part because x is used all over the place. However, it is pretty short and it only uses Python features that we have seen so far: assignment statements, expressions, function definitions, and function calls. We’re missing some information: Are all the x’s the same variable? Does Python make a new x for each assignment? For each function call? For each function definition?

Here’s the answer: whenever Python executes ...

Get Practical Programming, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.