$ show faif/python-patterns
The `faif/python-patterns` repository is a curated collection of Gang of Four (GoF) and other classic software design patterns, implemented in idiomatic Python. Each pattern is contained in a single, self-contained module under organized directories (creational, structural, behavioral, fundamental, other). The code is the ground truth: every module includes a `main()` function that runs doctests demonstrating usage, alongside dedicated unit tests in a parallel `tests/` directory. The implementations are not boilerplate; many demonstrate advanced Python features such as descriptors (strategy.py), metaclasses (registry.py), weak references (flyweight.py), context managers (pool.py), and closures (memento.py). The repo serves as a reference for learning or adopting design patterns in Python, with clear docstrings and examples from the Python ecosystem where applicable. It has no external runtime dependencies, relying solely on the Python standard library, making it universally applicable for study or light reuse.
The LLM identified 5 files worth highlighting for reuse:
Implements the Strategy pattern using a Python descriptor (DiscountStrategyValidator) to validate and attach discount strategies at assignment time. The descriptor ensures that an invalid discount (e.g., negative price) is rejected, gracefully falling back to None. This demonstrates non-obvious usage of descriptors for runtime constraint checking, and is fully self-containedβextractable for any project needing validated strategy injection.
Classic Flyweight pattern implemented via `__new__` and a `weakref.WeakValueDictionary` for the object pool. Objects are cached by a key (value+suit) and reused; the weak reference allows garbage collection when no external references remain. Shows advanced understanding of Python's object lifecycle and memory management. Completely standalone.
Provides three related constructs: a `memento` closure for saving/restoring object state, a `Transaction` class for batch rollback, and a `Transactional` decorator that wraps methods to auto-rollback on exceptions. The decorator uses the memento closure internally and is applied as a descriptor, demonstrating advanced decorator and closure patterns. All isolated and reusable.
An ObjectPool implementation using `queue.Queue` and the context manager protocol. Provides `__enter__`/`__exit__` for transparent check-out/check-in, and a `__del__` guard for automatic return if the pool object is garbage-collected. Clean, minimal, and easily adaptable for connection pools or any resource reuse.
Uses a metaclass (RegistryHolder) to automatically register every subclass into a class-level dictionary. The metaclass overrides `__new__` and stores the class by name. Demonstrates metaclass usage for declarative registration without decorators or manual steps. Self-contained and can be reused for plugin systems or class discovery.