⚡ Mid-Level Python — Complete Error List & Solutions

Mid-Level Python Error List & Architecture Fixes

All 16 essential Mid-Level Python errors covering LEGB closures, mutable defaults, dataclasses, C3 MRO, generators, context managers, and circular imports—with root reasons and live runnable fixes.

🚨 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__.