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, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.