Skip to content

Module 1: The Runtime & GIL (The Traffic Controller)

📚 Module 1: The Runtime & GIL

Course ID: PY-101
Subject: The Traffic Controller

Python is an Interpreted language. This means it doesn’t just turn into machine code once. It has a “Manager” (The Interpreter) that reads your code line by line and executes it.


🏗️ Step 1: Bytecode (The “Secret Language”)

When you run a .py file, Python first compiles it into Bytecode (the .pyc files you might see).

  • The Analogy: Imagine you write a recipe in English. Python translates it into a “Kitchen Language” that only the chef understands. This is faster for the chef to read than your original handwriting.

🏗️ Step 2: The GIL (The “One Chef” Rule)

The GIL (Global Interpreter Lock) is the most famous part of Python’s runtime.

🧩 The Analogy: The Single-Stove Kitchen

Imagine a kitchen with 10 chefs (Threads) but only One Stove (The CPU).

  • Only one chef can use the stove at a time.
  • If one chef is chopping vegetables (I/O work, like downloading a file), another chef can use the stove.
  • But if one chef is cooking a steak (CPU work, like math), everyone else has to wait.

Why do we do this? To keep memory safe. It’s easier to manage a kitchen if you only have one person cooking at a time.


🏗️ Step 3: Garbage Collection (The “Cleanup Crew”)

Python automatically cleans up memory you are no longer using.

🧩 The Analogy: The Hotel Maid

When you finish with an object (like a variable), Python’s “Maid” notices that nobody is using it anymore and throws it away to make room for new guests.

  • Reference Counting: If 0 people are looking at a variable, it gets deleted.

🧪 Step 4: Python Practice (Seeing Reference Counts)

Run this code to see how Python tracks “Who is looking” at an object.

import sys

# 1. Create a list
my_list = [1, 2, 3]

# 2. See how many references it has
# (It will be 2: one for 'my_list' and one for the 'getrefcount' function itself)
print(f"Initial references: {sys.getrefcount(my_list)}")

# 3. Create another reference
another_ref = my_list
print(f"After adding another reference: {sys.getrefcount(my_list)}")

🥅 Module 1 Review

  1. Interpreter: The program that reads and runs your Python code.
  2. Bytecode: The intermediate step between your code and the computer’s CPU.
  3. GIL: The rule that only one thread can run Python code at a time.
  4. Reference Counting: How Python knows when to delete things from memory.

:::tip Slow Learner Note You don’t need to fight the GIL. In Data Engineering and ML, we use libraries like NumPy that actually “step out of the kitchen” to use their own stoves (C/C++ code), allowing us to be very fast! :::