A compact, hands‑on lab designed to teach the Python object model through small, focused experiments. Each file isolates one concept: references, mutability, copying, circular references, garbage collection, and encapsulation.
This lab is ideal for systems architects, Python interview prep, and anyone who wants a deep, mechanical understanding of how Python objects behave under the hood
Lab Contents
- 01_function_arguments.py
- 02_mutable_defaults.py
- 03_identity_equality_hashing.py
- 04_hashable_custom_classes.py
- 05_copying_shallow_deep.py
- 06_object_lifecycle_gc.py
- 07_weakref_cache.py
- 08_stateful_fx_router.py
- 09_encapsulation.py
A small collection of example scripts that explore core Python object-model concepts: references, identity, mutability, copying, hashing, lifecycle, weak references, and simple encapsulation patterns.
-
01_function_arguments.py
Demonstrates references vs. rebinding, object identity (id()), and how in-place mutation differs from reassigning a name. -
02_mutable_defaults.py
Shows the mutable-default-argument pitfall and safe alternatives (e.g., useNone+ initializer). -
03_identity_equality_hashing.py
Explainsisvs==, equality semantics, and how hashing relates to equality (when to implement__eq__). -
04_hashable_custom_classes.py
Example of making custom classes hashable and the contract between__eq__and__hash__so objects can be used in sets/dicts. -
05_copying_shallow_deep.py
Demonstratescopy.copyvscopy.deepcopy, and when shallow copies share nested mutable objects. -
06_object_lifecycle_gc.py
Explores object creation, reference counting, finalizers (__del__) and the garbage collector. Showsgc.collect()for deterministic tests. -
07_weakref_cache.py
Illustrates usingweakref.WeakValueDictionaryfor caches that should not keep objects alive indefinitely. -
08_stateful_fx_router.py
A small dataclass-based example (Order + Router). Router takes deep copies of incoming orders for an audit log so later mutations don't alter recorded snapshots. -
09_encapsulation.py
Demonstrates basic encapsulation with private-by-convention attributes and property getters/setters that perform validation (e.g., age, department).
Run any example directly:
python3 /object_model_lab/01_reference_identity.py
Replace the filename as needed.
Recommended Python: 3.8+
- Many examples are intentionally simple to illustrate single concepts — adapt for production (validation, immutability, thread-safety, performance).
- For tests or deterministic GC behavior use `import gc; gc.collect()