Skip to content

mitrapinaki/object_model_lab

Repository files navigation

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

  1. 01_function_arguments.py
  2. 02_mutable_defaults.py
  3. 03_identity_equality_hashing.py
  4. 04_hashable_custom_classes.py
  5. 05_copying_shallow_deep.py
  6. 06_object_lifecycle_gc.py
  7. 07_weakref_cache.py
  8. 08_stateful_fx_router.py
  9. 09_encapsulation.py

Object Model Lab

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.

Files

  1. 01_function_arguments.py
    Demonstrates references vs. rebinding, object identity (id()), and how in-place mutation differs from reassigning a name.

  2. 02_mutable_defaults.py
    Shows the mutable-default-argument pitfall and safe alternatives (e.g., use None + initializer).

  3. 03_identity_equality_hashing.py
    Explains is vs ==, equality semantics, and how hashing relates to equality (when to implement __eq__).

  4. 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.

  5. 05_copying_shallow_deep.py
    Demonstrates copy.copy vs copy.deepcopy, and when shallow copies share nested mutable objects.

  6. 06_object_lifecycle_gc.py
    Explores object creation, reference counting, finalizers (__del__) and the garbage collector. Shows gc.collect() for deterministic tests.

  7. 07_weakref_cache.py
    Illustrates using weakref.WeakValueDictionary for caches that should not keep objects alive indefinitely.

  8. 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.

  9. 09_encapsulation.py
    Demonstrates basic encapsulation with private-by-convention attributes and property getters/setters that perform validation (e.g., age, department).

Usage

Run any example directly:

python3 /object_model_lab/01_reference_identity.py

Replace the filename as needed.

Recommended Python: 3.8+

Notes

  • 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()

About

A compact, hands‑on lab designed to teach the Python object model

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages