Heaps and stacks in Python

Heaps and stacks in Python
Photo by Victor Serban / Unsplash

TL;DR: Heaps are where a Python program stores its data. Stacks are where the computations happen. This post breaks down what happens in RAM when Python runs a simple script.

The Script:

name = "Eli"
x = 2 + 3
y = sorted([name, x])
  

Step 1: python script.py

When I first run the script via PowerShell:

  • The Windows kernel creates a Python process, allocates a memory block on RAM and provides the process with acces to that block via virtual memory.
  • Python:
    • creates heap memory in RAM that includes built-in functions, core class objects (e.g. list, dict), small integers, and other essential objects like True, False, and None.
    • creates the __main__ stack frame in memory.

Step 2: name = "Eli"

  • In heap memory, python creates a string object "Eli".
  • In stack, python creates and stores a reference to that object under the name name in the __main__ stack frame.

Step 3: x = 2 + 3

  • Python accesses the pre-stored interger objects 2 and 3 from heap, and adds them using a bytecode operation, and stores the result in the heap, if not already cached.
  • In the current stack frame, x is bound to the integer object 5.

Step 4: y = sorted([name, x])

  1. In heap, a new list object is created in heap memory for [name, x], referencing the existant values of name and x.
  2. In the current stack frame, the identifier y is created.
  3. Python creates a new temporary stack frame for the sorted() function, with a reference to the sorted function and a reference to the [name, x] list in heap memory.
  4. The sorted() frame is executed, and the result is popped out and stored in heap memory.
  5. The identifier y in the main stack frame is bound to the new sorted list object in heap.

By the end of this script, my __main__ stack frame contains three variables: name, x, and y, each pointing to heap-allocated objects: "Eli", 5, and [x, name].

Sources & Links

Related Posts