### Facade Pattern Implementation in Python Source: https://context7.com/faif/python-patterns/llms.txt Simplify a complex subsystem with a single entry point. This example provides a 'start' method to boot a simulated computer. ```python class CPU: def freeze(self) -> None: print("Freezing processor.") def jump(self, position: str) -> None: print(f"Jumping to: {position}") def execute(self) -> None: print("Executing.") class Memory: def load(self, position: str, data: str) -> None: print(f"Loading from {position} data: '{data}'.") class SolidStateDrive: def read(self, lba: str, size: str) -> str: return f"Some data from sector {lba} with size {size}" class ComputerFacade: """Simplified interface for computer boot""" def __init__(self): self.cpu = CPU() self.memory = Memory() self.ssd = SolidStateDrive() def start(self): self.cpu.freeze() self.memory.load("0x00", self.ssd.read("100", "1024")) self.cpu.jump("0x00") self.cpu.execute() # Usage - simple one-call interface computer = ComputerFacade() computer.start() # Output: # Freezing processor. # Loading from 0x00 data: 'Some data from sector 100 with size 1024'. # Jumping to: 0x00 # Executing. ``` -------------------------------- ### Proxy Pattern Implementation in Python Source: https://context7.com/faif/python-patterns/llms.txt Control access to an object by providing a surrogate. This example implements a proxy that logs access and restricts functionality to 'admin' users. ```python class Subject: def do_the_job(self, user: str) -> None: raise NotImplementedError() class RealSubject(Subject): """The actual job performer""" def do_the_job(self, user: str) -> None: print(f"I am doing the job for {user}") class Proxy(Subject): """Controls access to RealSubject with logging""" def __init__(self) -> None: self._real_subject = RealSubject() def do_the_job(self, user: str) -> None: print(f"[log] Doing the job for {user} is requested.") if user == "admin": self._real_subject.do_the_job(user) else: print("[log] I can do the job just for `admins`.") # Usage proxy = Proxy() proxy.do_the_job('admin') # Output: # [log] Doing the job for admin is requested. # I am doing the job for admin proxy.do_the_job('anonymous') # Output: # [log] Doing the job for anonymous is requested. # [log] I can do the job just for `admins`. ``` -------------------------------- ### Implement Strategy Pattern in Python Source: https://context7.com/faif/python-patterns/llms.txt The Strategy pattern allows algorithms to be selected at runtime. This example defines an `Order` class that can apply different discount strategies, such as a fixed percentage or a sale discount with an additional fixed amount. The discount logic is encapsulated in separate functions. ```python from __future__ import annotations from typing import Callable class Order: def __init__(self, price: float, discount_strategy: Callable = None) -> None: self.price = price self._discount_strategy = discount_strategy def apply_discount(self) -> float: if self._discount_strategy: discount = self._discount_strategy(self) else: discount = 0 return self.price - discount def __repr__(self) -> str: name = getattr(self._discount_strategy, "__name__", None) return f"" def ten_percent_discount(order: Order) -> float: return order.price * 0.10 def on_sale_discount(order: Order) -> float: return order.price * 0.25 + 20 ``` -------------------------------- ### Adapter Pattern Implementation in Python Source: https://context7.com/faif/python-patterns/llms.txt Use the Adapter pattern to make incompatible interfaces work together. This example unifies different animal sounds and human speech under a common 'make_noise' method. ```python from typing import Callable, Any class Dog: def __init__(self) -> None: self.name = "Dog" def bark(self) -> str: return "woof!" class Cat: def __init__(self) -> None: self.name = "Cat" def meow(self) -> str: return "meow!" class Human: def __init__(self) -> None: self.name = "Human" def speak(self) -> str: return "'hello'" class Adapter: """Adapts an object by replacing methods.""" def __init__(self, obj, **adapted_methods: Callable[..., Any]) -> None: self.obj = obj self.__dict__.update(adapted_methods) def __getattr__(self, attr: str) -> Any: return getattr(self.obj, attr) # Usage - unify different interfaces objects = [] dog = Dog() objects.append(Adapter(dog, make_noise=dog.bark)) cat = Cat() objects.append(Adapter(cat, make_noise=cat.meow)) human = Human() objects.append(Adapter(human, make_noise=human.speak)) for obj in objects: print(f"A {obj.name} goes {obj.make_noise()}") # Output: # A Dog goes woof! # A Cat goes meow! # A Human goes 'hello' ``` -------------------------------- ### Decorator Pattern Implementation in Python Source: https://context7.com/faif/python-patterns/llms.txt Dynamically add functionality to objects without altering their class. This example stacks bold and italic wrappers around text. ```python class TextTag: """Base text tag""" def __init__(self, text: str) -> None: self._text = text def render(self) -> str: return self._text class BoldWrapper(TextTag): """Wraps a tag in """ def __init__(self, wrapped: TextTag) -> None: self._wrapped = wrapped def render(self) -> str: return f"{self._wrapped.render()}" class ItalicWrapper(TextTag): """Wraps a tag in """ def __init__(self, wrapped: TextTag) -> None: self._wrapped = wrapped def render(self) -> str: return f"{self._wrapped.render()}" # Usage - decorators can be stacked simple_hello = TextTag("hello, world!") print(f"before: {simple_hello.render()}") # Output: before: hello, world! special_hello = ItalicWrapper(BoldWrapper(simple_hello)) print(f"after: {special_hello.render()}") # Output: after: hello, world! ``` -------------------------------- ### Implement Flyweight Pattern in Python Source: https://context7.com/faif/python-patterns/llms.txt The Flyweight pattern conserves memory by sharing common data between similar objects. This example uses `weakref.WeakValueDictionary` to pool card instances, ensuring that identical cards are represented by the same object in memory. ```python import weakref class Card: """Flyweight card - shared instances""" _pool: weakref.WeakValueDictionary = weakref.WeakValueDictionary() def __new__(cls, value: str, suit: str): obj = cls._pool.get(value + suit) if obj is None: obj = object.__new__(Card) cls._pool[value + suit] = obj obj.value, obj.suit = value, suit return obj def __repr__(self) -> str: return f"" # Usage - same cards share instances c1 = Card('9', 'h') c2 = Card('9', 'h') print(c1, c2) # Output: print(c1 == c2) # Output: True print(c1 is c2) # Output: True (same object) c3 = Card('A', 's') print(c1 is c3) # Output: False (different card) ``` -------------------------------- ### Implement Observer Pattern in Python Source: https://context7.com/faif/python-patterns/llms.txt The Observer pattern facilitates loose coupling by allowing objects (observers) to subscribe to state changes in another object (subject). When the subject's state changes, all its observers are automatically notified. This example demonstrates a `Data` subject notifying `DecimalViewer` and `HexViewer` observers. ```python from __future__ import annotations from typing import List class Observer: def update(self, subject: Subject) -> None: pass class Subject: def __init__(self) -> None: self._observers: List[Observer] = [] def attach(self, observer: Observer) -> None: if observer not in self._observers: self._observers.append(observer) def detach(self, observer: Observer) -> None: self._observers.remove(observer) def notify(self) -> None: for observer in self._observers: observer.update(self) class Data(Subject): def __init__(self, name: str = "") -> None: super().__init__() self.name = name self._data = 0 @property def data(self) -> int: return self._data @data.setter def data(self, value: int) -> None: self._data = value self.notify() class HexViewer: def update(self, subject: Data) -> None: print(f"HexViewer: Subject {subject.name} has data 0x{subject.data:x}") class DecimalViewer: def update(self, subject: Data) -> None: print(f"DecimalViewer: Subject {subject.name} has data {subject.data}") # Usage data = Data('Data 1') view1 = DecimalViewer() view2 = HexViewer() data.attach(view1) data.attach(view2) data.data = 10 data.detach(view2) data.data = 20 ``` -------------------------------- ### Swap Discount Strategies at Runtime Source: https://context7.com/faif/python-patterns/llms.txt Demonstrates how to dynamically change the discount strategy applied to an order object. ```python order = Order(100, discount_strategy=ten_percent_discount) print(order) # Output: print(order.apply_discount()) # Output: 90.0 order = Order(100, discount_strategy=on_sale_discount) print(order.apply_discount()) # Output: 55.0 order = Order(100) # No discount print(order.apply_discount()) # Output: 100 ``` -------------------------------- ### Dependency Injection Patterns in Python Source: https://context7.com/faif/python-patterns/llms.txt Demonstrates Constructor, Parameter, and Setter Injection for decoupling objects. Useful for enhancing testability and flexibility by passing dependencies to clients. ```python import datetime from typing import Callable class ConstructorInjection: def __init__(self, time_provider: Callable) -> None: self.time_provider = time_provider def get_current_time_as_html_fragment(self) -> str: current_time = self.time_provider() return f'{current_time}' class ParameterInjection: def get_current_time_as_html_fragment(self, time_provider: Callable) -> str: current_time = time_provider() return f'{current_time}' class SetterInjection: def set_time_provider(self, time_provider: Callable): self.time_provider = time_provider def get_current_time_as_html_fragment(self): current_time = self.time_provider() return f'{current_time}' # Stub for testing def midnight_time_provider() -> str: return "24:01" # Production provider def production_time_provider() -> str: now = datetime.datetime.now() return f"{now.hour}:{now.minute}" # Usage - Constructor Injection time_display = ConstructorInjection(midnight_time_provider) print(time_display.get_current_time_as_html_fragment()) # Output: 24:01 # Usage - Parameter Injection pi = ParameterInjection() print(pi.get_current_time_as_html_fragment(midnight_time_provider)) # Output: 24:01 # Usage - Setter Injection si = SetterInjection() si.set_time_provider(midnight_time_provider) print(si.get_current_time_as_html_fragment()) # Output: 24:01 ``` -------------------------------- ### State Pattern for Radio Tuning Source: https://context7.com/faif/python-patterns/llms.txt Demonstrates the State pattern by allowing a Radio object to change its behavior (AM/FM tuning) based on its internal state. ```python from __future__ import annotations class State: def scan(self) -> None: self.pos += 1 if self.pos == len(self.stations): self.pos = 0 print(f"Scanning... Station is {self.stations[self.pos]} {self.name}") class AmState(State): def __init__(self, radio: Radio) -> None: self.radio = radio self.stations = ["1250", "1380", "1510"] self.pos = 0 self.name = "AM" def toggle_amfm(self) -> None: print("Switching to FM") self.radio.state = self.radio.fmstate class FmState(State): def __init__(self, radio: Radio) -> None: self.radio = radio self.stations = ["81.3", "89.1", "103.9"] self.pos = 0 self.name = "FM" def toggle_amfm(self) -> None: print("Switching to AM") self.radio.state = self.radio.amstate class Radio: def __init__(self) -> None: self.amstate = AmState(self) self.fmstate = FmState(self) self.state = self.amstate def toggle_amfm(self) -> None: self.state.toggle_amfm() def scan(self) -> None: self.state.scan() # Usage radio = Radio() radio.scan() # Output: Scanning... Station is 1380 AM radio.scan() # Output: Scanning... Station is 1510 AM radio.toggle_amfm() # Output: Switching to FM radio.scan() # Output: Scanning... Station is 89.1 FM ``` -------------------------------- ### Factory Method Pattern in Python Source: https://context7.com/faif/python-patterns/llms.txt Demonstrates the Factory Method pattern using a factory function to create localizer objects based on language. This allows for flexible object creation. ```python from typing import Dict, Protocol, Type class Localizer(Protocol): def localize(self, msg: str) -> str: ... class GreekLocalizer: def __init__(self) -> None: self.translations = {"dog": "σκύλος", "cat": "γάτα"} def localize(self, msg: str) -> str: return self.translations.get(msg, msg) class EnglishLocalizer: def localize(self, msg: str) -> str: return msg def get_localizer(language: str = "English") -> Localizer: """Factory function that creates appropriate localizer""" localizers: Dict[str, Type[Localizer]] = { "English": EnglishLocalizer, "Greek": GreekLocalizer, } return localizers.get(language, EnglishLocalizer)() # Usage e = get_localizer(language="English") g = get_localizer(language="Greek") for msg in "dog parrot cat bear".split(): print(e.localize(msg), g.localize(msg)) # Output: # dog σκύλος # parrot parrot # cat γάτα # bear bear ``` -------------------------------- ### Builder Pattern in Python Source: https://context7.com/faif/python-patterns/llms.txt Illustrates the Builder pattern by separating the construction of complex objects from their representation. This allows for different representations using the same construction process. ```python class Building: def __init__(self) -> None: self.build_floor() self.build_size() def build_floor(self): raise NotImplementedError def build_size(self): raise NotImplementedError def __repr__(self) -> str: return f"Floor: {self.floor} | Size: {self.size}" class House(Building): def build_floor(self) -> None: self.floor = "One" def build_size(self) -> None: self.size = "Big" class Flat(Building): def build_floor(self) -> None: self.floor = "More than One" def build_size(self) -> None: self.size = "Small" # Alternative: External builder function class ComplexBuilding: def __repr__(self) -> str: return f"Floor: {self.floor} | Size: {self.size}" class ComplexHouse(ComplexBuilding): def build_floor(self) -> None: self.floor = "One" def build_size(self) -> None: self.size = "Big and fancy" def construct_building(cls) -> ComplexBuilding: building = cls() building.build_floor() building.build_size() return building # Usage house = House() print(house) # Output: Floor: One | Size: Big flat = Flat() print(flat) # Output: Floor: More than One | Size: Small complex_house = construct_building(ComplexHouse) print(complex_house) # Output: Floor: One | Size: Big and fancy ``` -------------------------------- ### Prototype Pattern Implementation Source: https://context7.com/faif/python-patterns/llms.txt Creates new objects by cloning existing instances. Useful when object creation is expensive. The `PrototypeDispatcher` manages and registers prototypes. ```python from __future__ import annotations from typing import Any class Prototype: def __init__(self, value: str = "default", **attrs: Any) -> None: self.value = value self.__dict__.update(attrs) def clone(self, **attrs: Any) -> Prototype: """Clone prototype and update attributes""" obj = self.__class__(**self.__dict__) obj.__dict__.update(attrs) return obj class PrototypeDispatcher: def __init__(self): self._objects = {} def get_objects(self) -> dict[str, Prototype]: return self._objects def register_object(self, name: str, obj: Prototype) -> None: self._objects[name] = obj def unregister_object(self, name: str) -> None: del self._objects[name] # Usage dispatcher = PrototypeDispatcher() prototype = Prototype() d = prototype.clone() a = prototype.clone(value='a-value', category='a') b = a.clone(value='b-value', is_checked=True) dispatcher.register_object('objecta', a) dispatcher.register_object('objectb', b) dispatcher.register_object('default', d) print([{n: p.value} for n, p in dispatcher.get_objects().items()]) # Output: [{'objecta': 'a-value'}, {'objectb': 'b-value'}, {'default': 'default'}] print(b.category, b.is_checked) # Output: a True ``` -------------------------------- ### Command Pattern for File Operations Source: https://context7.com/faif/python-patterns/llms.txt Implements the Command pattern to encapsulate file hiding and deletion operations, allowing for undo functionality. ```python from typing import List, Union class HideFileCommand: def __init__(self) -> None: self._hidden_files: List[str] = [] def execute(self, filename: str) -> None: print(f"hiding {filename}") self._hidden_files.append(filename) def undo(self) -> None: filename = self._hidden_files.pop() print(f"un-hiding {filename}") class DeleteFileCommand: def __init__(self) -> None: self._deleted_files: List[str] = [] def execute(self, filename: str) -> None: print(f"deleting {filename}") self._deleted_files.append(filename) def undo(self) -> None: filename = self._deleted_files.pop() print(f"restoring {filename}") class MenuItem: """The invoker - executes commands""" def __init__(self, command: Union[HideFileCommand, DeleteFileCommand]) -> None: self._command = command def on_do_press(self, filename: str) -> None: self._command.execute(filename) def on_undo_press(self) -> None: self._command.undo() # Usage delete_item = MenuItem(DeleteFileCommand()) hide_item = MenuItem(HideFileCommand()) delete_item.on_do_press('document.txt') # Output: deleting document.txt delete_item.on_undo_press() # Output: restoring document.txt hide_item.on_do_press('secret.txt') # Output: hiding secret.txt hide_item.on_undo_press() # Output: un-hiding secret.txt ``` -------------------------------- ### Publish-Subscribe Pattern in Python Source: https://context7.com/faif/python-patterns/llms.txt Implements the Publish-Subscribe pattern for loose coupling between publishers and subscribers via a message center. Publishers notify the message center, which then distributes messages to subscribed listeners. ```python from __future__ import annotations class Provider: def __init__(self) -> None: self.msg_queue = [] self.subscribers = {} def notify(self, msg: str) -> None: self.msg_queue.append(msg) def subscribe(self, msg: str, subscriber: Subscriber) -> None: self.subscribers.setdefault(msg, []).append(subscriber) def unsubscribe(self, msg: str, subscriber: Subscriber) -> None: self.subscribers[msg].remove(subscriber) def update(self) -> None: for msg in self.msg_queue: for sub in self.subscribers.get(msg, []): sub.run(msg) self.msg_queue = [] class Publisher: def __init__(self, msg_center: Provider) -> None: self.provider = msg_center def publish(self, msg: str) -> None: self.provider.notify(msg) class Subscriber: def __init__(self, name: str, msg_center: Provider) -> None: self.name = name self.provider = msg_center def subscribe(self, msg: str) -> None: self.provider.subscribe(msg, self) def run(self, msg: str) -> None: print(f"{self.name} got {msg}") # Usage message_center = Provider() fftv = Publisher(message_center) jim = Subscriber("jim", message_center) jim.subscribe("cartoon") jack = Subscriber("jack", message_center) jack.subscribe("music") fftv.publish("cartoon") fftv.publish("music") fftv.publish("cartoon") message_center.update() ``` -------------------------------- ### Borg (Monostate) Pattern Implementation Source: https://context7.com/faif/python-patterns/llms.txt The Borg pattern shares state across all instances. Changes to attributes are reflected across all objects. Use when singleton-like behavior is desired but distinct instances are acceptable. ```python from typing import Dict class Borg: _shared_state: Dict[str, str] = {} def __init__(self) -> None: self.__dict__ = self._shared_state class YourBorg(Borg): def __init__(self, state: str = None) -> None: super().__init__() if state: self.state = state elif not hasattr(self, "state"): self.state = "Init" def __str__(self) -> str: return self.state # Usage - all instances share state rm1 = YourBorg() rm2 = YourBorg() rm1.state = 'Idle' rm2.state = 'Running' print(f'rm1: {rm1}') # Output: rm1: Running print(f'rm2: {rm2}') # Output: rm2: Running # Instances are different objects but share state print(rm1 is rm2) # Output: False rm3 = YourBorg('Zombie') print(f'rm1: {rm1}') # Output: rm1: Zombie print(f'rm3: {rm3}') # Output: rm3: Zombie ``` -------------------------------- ### Object Pool Pattern Implementation Source: https://context7.com/faif/python-patterns/llms.txt Manages a pool of reusable objects to reduce creation/destruction overhead. Uses a queue to store and retrieve objects. The context manager ensures objects are returned to the pool. ```python from queue import Queue from types import TracebackType from typing import Union class ObjectPool: def __init__(self, queue: Queue, auto_get: bool = False) -> None: self._queue = queue self.item = self._queue.get() if auto_get else None def __enter__(self) -> str: if self.item is None: self.item = self._queue.get() return self.item def __exit__( self, Type: Union[type[BaseException], None], value: Union[BaseException, None], traceback: Union[TracebackType, None], ) -> None: if self.item is not None: self._queue.put(self.item) self.item = None # Usage import queue sample_queue = queue.Queue() sample_queue.put('connection_1') sample_queue.put('connection_2') # Use with context manager - automatically returns to pool with ObjectPool(sample_queue) as conn: print(f'Using: {conn}') # Output: Using: connection_1 # Object is returned to pool and can be reused with ObjectPool(sample_queue) as conn: print(f'Reusing: {conn}') # Output: Reusing: connection_1 ``` -------------------------------- ### Abstract Factory Pattern in Python Source: https://context7.com/faif/python-patterns/llms.txt Implements the Abstract Factory pattern using Python classes as factories. Useful for creating families of related objects without specifying concrete classes. ```python from typing import Type class Pet: def __init__(self, name: str) -> None: self.name = name def speak(self) -> None: raise NotImplementedError class Dog(Pet): def speak(self) -> None: print("woof") def __str__(self) -> str: return f"Dog<{self.name}>" class Cat(Pet): def speak(self) -> None: print("meow") def __str__(self) -> str: return f"Cat<{self.name}>" class PetShop: def __init__(self, animal_factory: Type[Pet]) -> None: self.pet_factory = animal_factory def buy_pet(self, name: str) -> Pet: pet = self.pet_factory(name) print(f"Here is your lovely {pet}") return pet # Usage cat_shop = PetShop(Cat) pet = cat_shop.buy_pet("Lucy") # Output: Here is your lovely Cat pet.speak() # Output: meow dog_shop = PetShop(Dog) pet = dog_shop.buy_pet("Max") # Output: Here is your lovely Dog pet.speak() # Output: woof ``` -------------------------------- ### Delegation Pattern in Python Source: https://context7.com/faif/python-patterns/llms.txt Implements the Delegation pattern using Python's dynamic features to achieve code reuse similar to inheritance. It forwards method calls to a delegate object. ```python from __future__ import annotations from typing import Any, Callable class Delegator: def __init__(self, delegate: Delegate) -> None: self.delegate = delegate def __getattr__(self, name: str) -> Any | Callable: attr = getattr(self.delegate, name) if not callable(attr): return attr def wrapper(*args, **kwargs): return attr(*args, **kwargs) return wrapper class Delegate: def __init__(self) -> None: self.p1 = 123 def do_something(self, something: str, kw=None) -> str: return f"Doing {something}{kw or ''}" # Usage delegator = Delegator(Delegate()) print(delegator.p1) # Output: 123 print(delegator.do_something("nothing")) # Output: Doing nothing print(delegator.do_something("something", kw=", today!")) # Output: Doing something, today! ``` -------------------------------- ### Iterator Pattern with Generators in Python Source: https://context7.com/faif/python-patterns/llms.txt Demonstrates the Iterator pattern using Python generators to traverse elements of a container without exposing its underlying representation. The `count_to` function yields elements one by one. ```python def count_to(count: int): """Counts by word numbers using a generator""" numbers = ["one", "two", "three", "four", "five"] yield from numbers[:count] # Usage print("Counting to two:") for number in count_to(2): print(number) print("\nCounting to five:") for number in count_to(5): print(number) ``` -------------------------------- ### Implement Composite Pattern in Python Source: https://context7.com/faif/python-patterns/llms.txt Use the Composite pattern to represent part-whole hierarchies. It allows clients to treat individual objects and compositions of objects uniformly. Requires defining a common interface for both individual objects and composite objects. ```python from abc import ABC, abstractmethod from typing import List class Graphic(ABC): @abstractmethod def render(self) -> None: raise NotImplementedError() class CompositeGraphic(Graphic): def __init__(self) -> None: self.graphics: List[Graphic] = [] def render(self) -> None: for graphic in self.graphics: graphic.render() def add(self, graphic: Graphic) -> None: self.graphics.append(graphic) def remove(self, graphic: Graphic) -> None: self.graphics.remove(graphic) class Ellipse(Graphic): def __init__(self, name: str) -> None: self.name = name def render(self) -> None: print(f"Ellipse: {self.name}") # Usage - build tree structure ellipse1, ellipse2, ellipse3, ellipse4 = Ellipse("1"), Ellipse("2"), Ellipse("3"), Ellipse("4") graphic1 = CompositeGraphic() graphic1.add(ellipse1) graphic1.add(ellipse2) graphic1.add(ellipse3) graphic2 = CompositeGraphic() graphic2.add(ellipse4) graphic = CompositeGraphic() graphic.add(graphic1) graphic.add(graphic2) graphic.render() ``` -------------------------------- ### Memento Pattern for State Management in Python Source: https://context7.com/faif/python-patterns/llms.txt Implements the Memento pattern to capture and restore an object's internal state. Useful for implementing undo functionality. The `Transaction` class provides a context manager for commit and rollback operations. ```python from copy import copy, deepcopy from typing import Any, Callable, List def memento(obj: Any, deep: bool = False) -> Callable: state = deepcopy(obj.__dict__) if deep else copy(obj.__dict__) def restore() -> None: obj.__dict__.clear() obj.__dict__.update(state) return restore class Transaction: """Transaction guard with commit/rollback""" def __init__(self, deep: bool, *targets: Any) -> None: self.deep = deep self.targets = targets self.commit() def commit(self) -> None: self.states = [memento(target, self.deep) for target in self.targets] def rollback(self) -> None: for a_state in self.states: a_state() class NumObj: def __init__(self, value: int) -> None: self.value = value def __repr__(self) -> str: return f"" def increment(self) -> None: self.value += 1 # Usage num_obj = NumObj(-1) transaction = Transaction(True, num_obj) try: for i in range(3): num_obj.increment() print(num_obj) transaction.commit() print('-- committed') for i in range(3): num_obj.increment() print(num_obj) num_obj.value += 'x' # This will fail except Exception: transaction.rollback() print('-- rolled back') print(num_obj) ``` -------------------------------- ### Chain of Responsibility for Request Handling Source: https://context7.com/faif/python-patterns/llms.txt Implements the Chain of Responsibility pattern to process requests through a series of handlers until one handles it. ```python from abc import ABC, abstractmethod from typing import Optional class Handler(ABC): def __init__(self, successor: Optional["Handler"] = None): self.successor = successor def handle(self, request: int) -> None: res = self.check_range(request) if not res and self.successor: self.successor.handle(request) @abstractmethod def check_range(self, request: int) -> Optional[bool]: pass class ConcreteHandler0(Handler): @staticmethod def check_range(request: int) -> Optional[bool]: if 0 <= request < 10: print(f"request {request} handled in handler 0") return True return None class ConcreteHandler1(Handler): start, end = 10, 20 def check_range(self, request: int) -> Optional[bool]: if self.start <= request < self.end: print(f"request {request} handled in handler 1") return True return None class FallbackHandler(Handler): @staticmethod def check_range(request: int) -> Optional[bool]: print(f"end of chain, no handler for {request}") return False ``` -------------------------------- ### Chain of Responsibility Pattern in Python Source: https://context7.com/faif/python-patterns/llms.txt Implements the Chain of Responsibility pattern to process requests through a series of handlers. Each handler decides whether to process the request or pass it to its successor. ```python h0 = ConcreteHandler0() h1 = ConcreteHandler1() h2 = FallbackHandler() h0.successor = h1 h1.successor = h2 for request in [2, 14, 22, 35]: h0.handle(request) ``` -------------------------------- ### Lazy Evaluation Pattern Implementation Source: https://context7.com/faif/python-patterns/llms.txt Delays expensive computations until needed and caches the result. The `lazy_property` decorator handles this for class attributes. ```python import functools from typing import Callable, Type class lazy_property: def __init__(self, function: Callable) -> None: self.function = function functools.update_wrapper(self, function) def __get__(self, obj, type_: Type) -> str: if obj is None: return self val = self.function(obj) obj.__dict__[self.function.__name__] = val return val class Person: def __init__(self, name: str, occupation: str) -> None: self.name = name self.occupation = occupation @lazy_property def relatives(self) -> str: # Expensive computation - only runs once print("Computing relatives...") return "Many relatives." # Usage john = Person('John', 'Coder') print(john.name) # Output: John print('relatives' in john.__dict__) # Output: False # First access triggers computation print(john.relatives) # Output: Computing relatives... # Output: Many relatives. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.