"> ">
⚑ Track 03 β€” Mid-Level Masterclass

Object Model, Scopes & Memory Internals

Understand LEGB scope lookup rules, dynamic namespaces, reference counting pointers, shallow vs deep cloning, and CPython's generational Garbage Collector (`gc`).

πŸ‘οΈ Views: 3,350 Page Views
⚑ Mid-Level Python Interactive Studio

Interactive Sandbox Studio: 4 Tracks & 26 Competencies

πŸ‘οΈ 3,350 Total Page Views

Switch tracks and select any of the 26 core topics below to run production Python code, inspect CPython memory mechanics, and execute unit test assertion suites in real time.

πŸ“Œ Select Topic (26 Total): Showing 5 Topics for Track 03
⚑ Topic 21 of 26 ⏱️ 5 min interactive
Module 21 of 26

21. Namespaces & LEGB Scope Resolution

Python resolves variable names using the LEGB rule: Local, Enclosing, Global, Built-in. Use global and nonlocal keywords to mutate outer scopes.

πŸ’‘ Core Engineering Principles

  • LEGB Lookup Chain: Scope lookup cascades from Local to Built-in.
  • nonlocal Keyword: Allows mutating enclosing closure variables without global scope pollution.
  • globals() & locals(): Inspect active runtime namespaces as standard dictionaries.
middle_namespaces_legb.py
Ready (Python 3.13 Active)
πŸ–₯️ Execution Output & Test Results stdout
Click "β–Ά Run Code" to execute this Mid-Level Python module or "πŸ§ͺ Run Unit Tests" to verify with pytest.
🚨 Mid-Level Python Complete Error List (16 Errors, Root Reasons & Solutions) β€” Click to Expand
🚨 Complete Python Error List, Root Causes & Production Solutions

⚑ Mid-Level Python Architecture & OOP Error Encyclopedia

Every Mid-Level (16) Python exception explained with its exact root reason, step-by-step fix, side-by-side ❌ Broken vs. βœ… Fixed Code, and 1-click Live Python Execution.

πŸ”
Showing Level Errors
πŸ“‹ Quick-Reference Summary Table: Mid-Level Python Errors (16)
Level Exception / Error Root Reason (Why It Happens) Production Solution (How to Fix)
Mid-LevelUnboundLocalError: cannot access local variable before assignmentWhen Python compiles a function body, any variable assigned anywhere inside the function (e.g., count += 1) is marked as a LOCAL variable for the entire function. Reading it before that assignment raises UnboundLocalError even if a global or enclosing variable of the same name exists.Pass state explicitly as function arguments, or declare 'nonlocal var' (for enclosing closures) or 'global var' (for module globals) before mutating.
Mid-LevelMutable Default Argument Trap (Shared State Bug)Default parameter values in Python are evaluated ONCE when the 'def' statement is executed, not each time the function is called. Using a mutable default (def append_tag(tag, tags=[]):) causes every caller that omits 'tags' to mutate the exact same list object in memory!Always use None as the default value (tags: list[str] | None = None) and instantiate a fresh list inside the function body.
Mid-LevelValueError: mutable default <class 'list'> for field is not allowedPython's @dataclass explicitly raises a ValueError at class creation time if you assign a mutable default (like list, dict, or set) directly to a field, protecting you from shared mutable state across instances.Import 'field' from dataclasses and use field(default_factory=list) or field(default_factory=dict).
Mid-Leveldataclasses.FrozenInstanceError: cannot assign to fieldAttempting to mutate an attribute on a dataclass decorated with @dataclass(frozen=True). Frozen dataclasses override __setattr__ to enforce immutability and hashability.Use dataclasses.replace(instance, field=new_val) to create a new updated instance while preserving immutability.
Mid-LevelRuntimeError: dictionary / set changed size during iterationAdding or deleting keys from a dictionary or set while iterating directly over its live view (for k in my_dict:) invalidates internal hash table pointers and raises RuntimeError.Iterate over a snapshot list of keys (for k in list(my_dict):) when deleting in place, or build a filtered dictionary using a dict comprehension.
Mid-LevelLate-Binding Closure Trap in Loops (Lambdas / Functions)Closures capture variables by reference (cell objects), not by value. Creating functions or lambdas inside a loop (e.g., [lambda x: x * i for i in range(4)]) causes all functions to look up the final value of 'i' after the loop finishes!Bind the loop variable eagerly as a default parameter (lambda x, i=i: x * i) or use functools.partial.
Mid-LevelShallow Copy Nested Mutation Bug (copy.copy vs copy.deepcopy)A shallow copy (dict.copy(), list[:], or copy.copy()) only duplicates the outer container; nested lists or dicts inside still point to the exact same memory addresses (id()).Use copy.deepcopy(obj) when cloning nested data structures so inner mutable objects are recursively duplicated.
Mid-LevelTypeError: Can't instantiate abstract class with abstract methodA subclass inheriting from an Abstract Base Class (abc.ABC) failed to implement one or more methods decorated with @abstractmethod.Implement every @abstractmethod defined on the parent ABC with a matching signature in the concrete subclass.
Mid-LevelTypeError: Cannot create a consistent method resolution order (MRO)In multiple inheritance, listing a base class before its own subclass (e.g., class C(Base, SubOfBase):) violates Python's C3 Linearization monotonicity rule because Base would precede SubOfBase.Always order more-specific subclasses BEFORE their parent base classes in the inheritance tuple, or favor composition over deep multiple inheritance.
Mid-LevelRecursionError in @property Getter/SetterInside a @property getter or setter named 'price', reading or assigning 'self.price' instead of the backing attribute 'self._price' calls the property getter/setter recursively until stack overflow.Store the underlying data on a private backing attribute prefixed with an underscore (self._price) inside the @property methods.
Mid-LevelGenerator Exhaustion Bug (Silent Empty Second Iteration)Generators and iterators (including map(), filter(), zip()) are single-pass streams. Once iterated over (e.g., via sum(gen) or list(gen)), the generator is permanently exhausted and any subsequent loop yields 0 items without raising an error.Convert to a tuple/list if you need multiple passes over small data, or pass a callable factory / re-invoke the generator function for each pass.
Mid-LevelRuntimeError: generator didn't stop after throw() / didn't yieldIn a @contextlib.contextmanager function, if the code inside the 'with' block raises an exception and your generator catches it without re-raising OR yields a second time, contextlib raises RuntimeError.Wrap the single 'yield' inside a 'try:... finally:...' block in @contextmanager so cleanup always runs and exceptions propagate naturally.
Mid-LevelDecorator Metadata Loss (Missing @functools.wraps)Writing a decorator wrapper without @functools.wraps(func) overwrites the original function's __name__, __doc__, and __annotations__ with 'wrapper', breaking FastAPI route inspection, Sphinx docs, and pytest fixtures.Always decorate inner wrapper functions with @functools.wraps(func).
Mid-LevelImportError: cannot import name '...' from partially initialized module (Circular Import)Module A imports Module B at top-level while Module B also imports Module A at top-level. Whichever module is imported second sees the first module before it has finished executing its top-level class/function definitions.Extract shared models/interfaces into a third base module (e.g., schemas.py or protocols.py), or use 'from __future__ import annotations' with 'if TYPE_CHECKING:' for type-only imports.
Mid-Leveljson.decoder.JSONDecodeError / TypeError: Object of type datetime is not JSON serializablejson.loads() fails with JSONDecodeError on empty strings, single quotes, or trailing commas; json.dumps() fails with TypeError on datetime, UUID, Decimal, or custom objects.Validate non-empty payloads before json.loads(), and pass default=str (or a custom encoder / Pydantic .model_dump_json()) to json.dumps().
Mid-LevelLost Exception Context (Raising Without 'from err')Catching a low-level exception and raising a custom domain exception via 'raise ServiceError(...)' without chaining hides the original traceback root cause.Always use 'raise DomainError(...) from err' to preserve the cause chain in __cause__.
πŸ“š Complete Mid-Level Python Curriculum Reference (26 Core Engineering Topics)

This interactive Mid-Level Python Systems Studio covers 26 production engineering modules across 4 specialized tracks:

  • Track 01 β€” Functions, Closures & Decorators (Topics 1–12): Argument unpacking (*args, **kwargs), positional-only and keyword-only parameters, first-class functions, lexical closures, functools.wraps decorators, parameterized decorators, lru_cache memoization, generator functions (yield), generator expressions, itertools pipelines, lambda expressions, and functools.partial.
  • Track 02 β€” Object-Oriented Design, Dataclasses & Typing (Topics 13–20): Immutable @dataclass(frozen=True) and field(default_factory=...), @property getters and validation setters, @classmethod and @staticmethod factories, Abstract Base Classes (abc.ABC), structural subtyping with typing.Protocol, Method Resolution Order (C3 Linearization & super()), magic dunder methods (__repr__, __eq__, __lt__), and Generic type variables (TypeVar, Generic[T]).
  • Track 03 β€” CPython Memory Model, Namespaces & References (Topics 21–25): Namespaces and the LEGB scope resolution rule (Local, Enclosing, Global, Built-in), mutable vs. immutable object identity, shallow copy vs. deep copy semantics (copy.deepcopy), CPython PyObject headers and reference counting (sys.getrefcount), and cyclic garbage collection with weak references (gc, weakref).
  • Track 04 β€” Exception Architecture & Context Managers (Topic 26): Designing domain-specific custom exception hierarchies, explicit exception chaining (raise CustomError from exc), and deterministic resource cleanup with custom context managers (__enter__ / __exit__ and @contextlib.contextmanager).
⚑ 30-Second Developer Summary

CPython Memory Architecture & References

  • Variables are Labels, Not Boxes: In CPython, variables point to heap-allocated `PyObject` structs. Immutable objects (`int`, `str`, `tuple`) cannot be changed in place; mutating them creates a new object memory address.
  • Memory Management Mechanics: CPython manages memory using immediate **Reference Counting** supplemented by a **3-Generation Cyclic Garbage Collector** (`gc`) that detects and destroys reference cycles.

1. Namespaces & LEGB Scope Resolution

Python resolves variable names in strict order: Local → Enclosing → Global → Built-in. Use `nonlocal` to bind variables in enclosing nested closures.

# Global Scope
config_setting = "PRODUCTION"

def outer_service():
    # Enclosing Scope
    request_count = 0

    def inner_counter():
        nonlocal request_count  # Bind to enclosing variable
        request_count += 1
        return request_count

    return inner_counter

counter = outer_service()
print("Call 1:", counter())  # 1
print("Call 2:", counter())  # 2

2. Shallow vs Deep Copying (`copy.copy` vs `copy.deepcopy`)

A shallow copy (`copy.copy()`) creates a new outer container but copies references to nested objects. A deep copy (`copy.deepcopy()`) recursively clones all nested objects.

import copy

original = [1, 2, [3, 4]]

# Shallow Copy: Outer list is copied, inner list is shared reference
shallow = copy.copy(original)
shallow[2].append(99)
print("Original after shallow mutation:", original)  # [1, 2, [3, 4, 99]]

# Deep Copy: Independent recursive clone
deep = copy.deepcopy(original)
deep[2].append(100)
print("Original after deep mutation:", original)     # [1, 2, [3, 4, 99]]
print("Deep object:", deep)                           # [1, 2, [3, 4, 99, 100]]

3. Reference Counting & Garbage Collection (`sys.getrefcount`, `gc`)

Every `PyObject` tracks its reference count. When the count reaches zero, memory is freed immediately. Cyclic references are reclaimed by CPython's generational GC scanner.

import sys
import gc

data = ["heavy_payload_block"]
print("Initial Ref Count:", sys.getrefcount(data) - 1)  # 1

alias = data
print("Ref Count after alias:", sys.getrefcount(data) - 1)  # 2

del alias
print("Ref Count after del alias:", sys.getrefcount(data) - 1)  # 1

# Manually inspect & trigger Garbage Collection
collected = gc.collect()
print("GC Collected Objects:", collected)

⭐ Rate Track 03: Object Model & Memory Mechanics (1 to 5 Stars)

Your rating is stored directly in the database. Average: 4.9 / 5 (1 rating)

β˜… β˜… β˜… β˜… β˜…
← Track 02: Advanced OOP Next Track: Exception Architecture β†’