Python Masterclass / Module 4 of 10 Phase 2: Language Core & CPython Internals

Language Fundamentals, Call-by-Sharing, LEGB Scoping & Modern Type System (PEP 484–695)

28 min study + 2 Live Wasm Labs
⚡ Answer-First Executive Summary (TL;DR) Module 4 Key Takeaways
  • ✓ Python variables are not C memory boxes—they are lexical names bound to PyObject* pointers. Passing arguments uses Call-by-Object-Reference (Call-by-Sharing): mutating a passed list mutates the caller’s object, while reassigning the parameter name only rebinds the local pointer.
  • ✓ Scope resolution strictly follows LEGB: Local (function fast locals) → Enclosing (closure cell objects) → Global (module dict) → Built-in (builtins module).
  • ✓ Default function arguments are evaluated ONCE when the def statement executes, not on each call—never use a mutable literal (def fn(items=[])) as a default.
  • ✓ Modern Python typing (3.10–3.14) uses native unions (T | None), PEP 695 generic syntax (def first[T](seq: Sequence[T]) -> T), and typing.Protocol for structural duck typing.

01. Names, Objects & Call-by-Object-Reference (Call-by-Sharing)

In C or Rust, int x = 42; names a fixed 4-byte stack memory address, and x = 99; overwrites those 4 bytes in place. In Python, every value is a heap-allocated PyObject, and variables are merely labels (dictionary keys or local fast-array slots) pointing to those objects.

  [ Stack Frame Fast Locals ]                  [ CPython Heap (PyObject*) ]
  ┌─────────────────────────┐                  ┌──────────────────────────────────────┐
  │ a ──────────────────────┼─────────────────▶│ PyListObject @ 0x7f8a10 (refcnt = 2) │
  │ b ──────────────────────┼─────────────────▲│   ob_item ──▶ [ Ptr(10), Ptr(20) ]   │
  └─────────────────────────┘                  └──────────────────────────────────────┘
  • b = a        ➜ Copies the pointer (0x7f8a10) and increments ob_refcnt to 2.
  • b.append(30) ➜ Mutates PyListObject @ 0x7f8a10 in-place (both 'a' and 'b' see [10, 20, 30]).
  • b = [99]     ➜ Rebinds 'b' to a brand-new PyListObject @ 0x7f8b90 ('a' still points to 0x7f8a10).
Classic Bug #1: Mutable Default Arguments

Default values in def add_tag(tag: str, tags: list[str] = []) are evaluated once at module import time and stored in add_tag.__defaults__. Every call that omits tags mutates the exact same list across requests! Always default to None and initialize inside the body.

Classic Bug #2: 2D Matrix Row Aliasing ([[0]*C]*R)

Writing grid = [[0] * 3] * 4 creates an outer list containing 4 pointers to the exact same inner list. Setting grid[0][0] = 1 mutates row 0, 1, 2, and 3 simultaneously! Always use [[0] * 3 for _ in range(4)].

02. LEGB Scope Resolution, Closures & Complete Signature Grammar

When you reference a name in Python, the compiler and runtime resolve it across four nested namespaces—LEGB:

Table 4.1 — CPython LEGB Scope Hierarchy & Bytecode Instructions
Scope Tier Bytecode Opcode Internal Storage Write / Rebind Modifier
1. Local (L) LOAD_FAST / STORE_FAST Contiguous C array localsplus[] on stack frame (O(1) index offset — no hash lookup!) Default inside def upon assignment (x = 1)
2. Enclosing (E) LOAD_DEREF / STORE_DEREF PyCellObject tuple stored in fn.__closure__ Requires nonlocal x to rebind outer variable
3. Global (G) LOAD_GLOBAL / STORE_GLOBAL Module dictionary module.__dict__ (cached via inline PEP 659 version tags) Requires global x to rebind module variable
4. Built-in (B) LOAD_GLOBAL (fallback) builtins.__dict__ (len, range, Exception) Never shadow builtins (e.g. avoid naming variables list, id, type)

The Complete Python 3.8+ Function Parameter Grammar (/ and *)

def invoke_model(
    model_id: str,          # Positional-ONLY (before '/'): callers cannot pass model_id="gpt"
    prompt: str,
    /,                      # ◀── Positional-only boundary (PEP 570)
    temperature: float = 0.2, # Positional-or-Keyword
    *extra_stops: str,      # Var-positional tuple (*args)
    max_tokens: int = 1024, # Keyword-ONLY (after '*'): callers MUST pass max_tokens=2048
    stream: bool = False,
    **metadata: object,     # Var-keyword dict (**kwargs)
) -> dict[str, object]:
    ...

03. Modern Type System: PEP 695 Generics, Protocol, TypedDict & TypeIs (PEP 742)

In production AI and backend systems, type annotations serve a dual role: compile-time verification via pyright/mypy AND runtime schema introspection via typing.get_type_hints() (used by FastAPI, Pydantic, and MCP tool registries).

from typing import Annotated, Final, Literal, Protocol, TypedDict, overload, runtime_checkable

# 1. Structural Subtyping (Static Duck Typing without inheritance)
@runtime_checkable
class VectorIndex(Protocol):
    def search(self, query_vec: list[float], top_k: int = 5) -> list[str]: ...

# 2. TypedDict for zero-overhead JSON dictionary typing
class ToolCallEvent(TypedDict):
    type: Literal["tool_call", "final_answer"]
    tool_name: str
    args: dict[str, object]

# 3. PEP 695 (Python 3.12+) Native Generic Type Parameter Syntax & Type Alias
type JSONValue = dict[str, "JSONValue"] | list["JSONValue"] | str | int | float | bool | None

class BoundedCache[K, V]:
    MAX_LIMIT: Final[int] = 10_000

    def __init__(self, capacity: int) -> None:
        self.capacity = min(capacity, self.MAX_LIMIT)
        self._store: dict[K, V] = {}

    def get(self, key: K) -> V | None:
        return self._store.get(key)

04. Complete Lexical Grammar: All 35 Hard Keywords, 4 Soft Keywords & Operator Semantics

Python’s PEG grammar defines 35 reserved hard keywords (keyword.kwlist) and 4 contextual soft keywords (keyword.softkwlist: match, case, type, _—which act as keywords only in their grammatical clauses and remain valid variable names elsewhere!). Every subtlety of Python’s operator and statement semantics is summarized below:

Table 4.2 — Complete Python Syntax & Execution Semantics Matrix
Language Construct Syntax / Grammar Exact Runtime Semantics & Edge Cases
35 Hard + 4 Soft Keywords import keyword; keyword.kwlist Singletons: None, True, False • Boolean/Logic: and, or, not, in, is • Control: if, elif, else, for, while, break, continue, pass • Exceptions: try, except, finally, raise, assert • Definitions/Scope: def, return, lambda, yield, class, del, global, nonlocal, import, from, as, with, async, await • Soft (3.10–3.12+): match, case, type, _.
Short-Circuit Value Logic x or default / a and b and / or return the actual evaluated operand object, not a coerced boolean! "" or "fallback" returns "fallback". Truthiness checks __bool__() first, falling back to __len__() != 0.
Floor Division, Modulo & MatMul a // b, a % b, divmod(a, b), A @ B // floors toward -∞ (so -7 // 2 == -4, unlike C’s truncation to -3), preserving the Euclidean invariant (a // b) * b + (a % b) == a where a % b always has the sign of divisor b. @ invokes __matmul__ (PEP 465).
Chained Comparisons & Walrus 0 <= x < n and (m := pattern.match(s)) Chained comparisons a < f(x) < b evaluate the middle expression f(x) exactly once. The Walrus operator := (PEP 572) binds and returns a value inside an expression scope.
Extended Unpacking & Slicing head, *mid, tail = seq; a[start:stop:step] Starred assignment packs excess items into a list. Slices compile to slice(start, stop, step) objects; slice assignment lst[1:3] = [9, 8, 7] mutates list length in-place; ... is the Ellipsis singleton.
String Literals & PEP 750 t-strings f"{x=:.2f}", r"\d+", b"\x89PNG", t"SQL {v}" f-strings support f"{expr=}" debug output, !r/!s/!a conversions, and nested format specs. Python 3.14 PEP 750 Template Strings (t"...") evaluate to a structured Template object separating static strings from interpolations to prevent SQL/XSS injection.
Loop else & Exception Chaining for x in items: ... else: ... / raise E from cause A for/while ... else: block executes only if the loop completed normally without hitting break. raise NewError from orig sets __cause__; raise NewError from None hides noisy inner tracebacks; err.add_note("ctx") (PEP 678) attaches diagnostic notes.

💻 Hands-On WebAssembly Python Labs (Module 4)

Click Run & Edit Live (Wasm) on any lab below to execute and modify the code in our browser Pyodide runtime.

▶ Interactive Wasm Lab

Lab 4.1: Proving Call-by-Sharing, Mutable Default Pitfalls & Closure Cell Mechanics

Run this live lab to inspect function __defaults__, closure PyCellObject contents (__closure__), and the exact difference between late-binding and early-bound closures.

# 1. Inspecting Mutable Default Argument Persistence (__defaults__)
def broken_append(item: str, bucket: list[str] = []) -> list[str]:
    bucket.append(item)
    return bucket

print("[1] Mutable Default Argument Trap:")
print("    Call 1:", broken_append("alpha"))
print("    Call 2:", broken_append("beta"))  # Surprising! Reuses same list in __defaults__
print("    fn.__defaults__ tuple:", broken_append.__defaults__)

# Safe Pythonic pattern: None sentinel
def safe_append(item: str, bucket: list[str] | None = None) -> list[str]:
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

print("    Safe Call 1 & 2:", safe_append("alpha"), safe_append("beta"))

# 2. Late-Binding Closures vs. Default-Parameter Early Binding
late_funcs = [lambda x: x * i for i in range(4)]
early_funcs = [lambda x, factor=i: x * factor for i in range(4)]

print("\n[2] Closure Late-Binding in Loops:")
print("    Late-bound (all use final i=3):", [f(10) for f in late_funcs])
print("    Cell object captured by late_funcs[0]:", late_funcs[0].__closure__[0].cell_contents)
print("    Early-bound via default arg:    ", [f(10) for f in early_funcs])

# 3. Stateful Closure using 'nonlocal'
def make_token_meter(budget: int):
    consumed = 0
    def record(tokens: int) -> tuple[int, int]:
        nonlocal consumed
        consumed += tokens
        return consumed, budget - consumed
    return record

meter = make_token_meter(1000)
print("\n[3] Nonlocal Closure State:", meter(250), "->", meter(400))
▶ Interactive Wasm Lab

Lab 4.2: Structural Pattern Matching (match/case) & Runtime Protocol Verification

Execute PEP 634 structural pattern matching with destructuring and guards alongside @runtime_checkable typing.Protocol verification.

from dataclasses import dataclass
from typing import Protocol, runtime_checkable

@runtime_checkable
class RunnableTool(Protocol):
    name: str
    def invoke(self, payload: dict) -> str: ...

@dataclass
class SqlQueryTool:
    name: str = "postgres_readonly"
    def invoke(self, payload: dict) -> str:
        return f"Executed SQL: {payload.get('sql')}"

def dispatch_agent_event(event: dict) -> str:
    # PEP 634 Structural Pattern Matching with mapping destructuring + guard clause
    match event:
        case {"type": "tool_call", "tool": str(name), "args": {"sql": str(query)}} if query.upper().startswith("SELECT"):
            return f"[ALLOW] Read-only query on {name}: {query}"
        case {"type": "tool_call", "tool": str(name), "args": {"sql": str(query)}}:
            return f"[BLOCK] Mutating SQL rejected by guardrail: {query}"
        case {"type": "final", "tokens": int(t), "answer": str(ans)} if t < 4096:
            return f"[DONE ({t} tok)] {ans}"
        case _:
            return "[ERROR] Unrecognized event schema"

tool = SqlQueryTool()
print("Satisfies RunnableTool Protocol (without inheritance!)?", isinstance(tool, RunnableTool))
print("-" * 64)
events = [
    {"type": "tool_call", "tool": "db", "args": {"sql": "SELECT id FROM users LIMIT 5"}},
    {"type": "tool_call", "tool": "db", "args": {"sql": "DROP TABLE users"}},
    {"type": "final", "tokens": 312, "answer": "Found 5 active users."},
]
for ev in events:
    print(dispatch_agent_event(ev))
▶ Interactive Wasm Lab

Lab 4.3: Complete Syntax & Semantics Verification (Keywords, Walrus, Unpacking, for-else & Exception Notes)

Execute a live tour of Python’s core lexical and semantic features: keyword introspection, Euclidean floor/modulo invariants, extended star unpacking, slice objects, for...else search completion, and PEP 678 exception notes.

import keyword

# 1. All Hard & Contextual Soft Keywords in Python
print(f"[1] Hard Keywords ({len(keyword.kwlist)}):", ", ".join(keyword.kwlist[:12]), "...")
print(f"    Soft Keywords ({len(keyword.softkwlist)}):", keyword.softkwlist)

# 2. Euclidean Floor Division (//) & Modulo (%) Invariant vs. C Truncation
a, b = -7, 2
q, r = divmod(a, b)
assert (a // b) * b + (a % b) == a
print(f"\n[2] Euclidean Invariant for (-7, 2): divmod={q, r} -> ({q}*{b} + {r} == {a})")

# 3. Extended Iterable Unpacking, Slice Objects & Dict Merge (PEP 584)
records = [10, 20, 30, 40, 50, 60]
first, second, *middle, last = records
REV_EVERY_TWO = slice(None, None, -2)
merged_cfg = {"host": "localhost", "retries": 2} | {"retries": 5, "tls": True}
print(f"\n[3] Star Unpacking: first={first}, middle={middle}, last={last}")
print(f"    Named Slice Object records[REV_EVERY_TWO]: {records[REV_EVERY_TWO]}")
print(f"    PEP 584 Dict Union (|): {merged_cfg}")

# 4. 'for ... else' Semantics + Walrus Assignment Expression (:=)
primes_checked = []
target = 29
for divisor in range(2, int(target ** 0.5) + 1):
    if (rem := target % divisor) == 0:
        print(f"    Composite factor found: {divisor}")
        break
    primes_checked.append((divisor, rem))
else:
    # Runs ONLY because 'break' was never triggered!
    print(f"\n[4] for...else Clause Executed: {target} is prime (tested divisors: {primes_checked})")

# 5. Exception Chaining (__cause__) & PEP 678 .add_note()
try:
    try:
        int("not_an_int")
    except ValueError as orig:
        err = RuntimeError("Failed to parse agent tool payload")
        err.add_note("Context: tool_name='calculator', field='amount'")
        raise err from orig
except RuntimeError as caught:
    print(f"\n[5] Caught Chained Exception: {caught!r}")
    print(f"    Explicit __cause__: {caught.__cause__!r}")
    print(f"    PEP 678 __notes__:  {caught.__notes__}")

Frequently Asked Staff Interview Questions (Module 4)

Is Python pass-by-value or pass-by-reference? ▸

Neither in the C++ sense: Python is Call-by-Object-Reference (coined "Call-by-Sharing" by Barbara Liskov). When you call f(x), the parameter inside f receives a copy of the PyObject* pointer that x points to. If the object is mutable (like a list or dict), in-place operations (x.append(1)) are visible to the caller. If you assign x = [9, 9] inside f, it only rebinds the local variable x to a new PyObject*.

Why do lambdas defined inside a for-loop all use the last loop value, and how do you fix it? ▸

Closures in Python capture variable names (via PyCellObject references to the enclosing scope), NOT the value at the moment the lambda is created (late binding). By the time the lambdas are called after the loop finishes, the loop variable holds its final iteration value. Fix it by binding the current value as a default parameter: [lambda x, i=i: x + i for i in range(5)].

What is the difference between typing.Protocol and abc.ABC? ▸

abc.ABC enforces nominal subtyping: a class must explicitly inherit from the ABC (class MyStore(BaseStore)) to pass isinstance/type checks. typing.Protocol enforces structural subtyping (static duck typing): any class that implements the required methods/attributes satisfies the Protocol automatically without inheritance.