Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
Borg pattern shared state in Python
Implement the Borg pattern to share state across class instances by assigning a class-level dictionary to each instance's __dict__.
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = Borg._shared_state
class ConfigManager(Borg):
def __init__(self):
super().__init__()
if not hasattr(self, "settings"):
self.settings = {}
def set(self, key, value):
self.settings[key] = va…
Bridge Pattern in Python: Separate Abstraction from Implementation
Implement the Bridge design pattern in Python so that an abstraction (remote control) can operate on different device implementations independently.
class RemoteControl:
"""Abstraction: controls a device without knowing implementation details."""
def __init__(self, device):
self.device = device
def toggle_power(self):
if self.device.is_enabled():
self.device.disable()
return "Power off"
else:
…
Composable Predicates with the &, |, ~ Operators in Python
Define a reusable Predicate class that combines boolean checks with & (AND), | (OR), and ~ (NOT) operators.
class Predicate:
def __init__(self, func, name=None):
self.func = func
self.name = name or getattr(func, "__name__", "predicate")
def __call__(self, value):
return self.func(value)
def __and__(self, other):
return Predicate(lambda v: self(v) and other(v), f"({self.name} AN…
How to Implement the Command Pattern with Undo in Python
Python code demonstrating the Command design pattern with undo and redo support using action objects and a history manager.
class Command:
def execute(self):
raise NotImplementedError
def undo(self):
raise NotImplementedError
class AddTextCommand(Command):
def __init__(self, document, text):
self.document = document
self.text = text
def execute(self):
self.document.append(self.tex…
How to Implement the State Pattern in Python
Implement the State design pattern in Python by delegating behavior to state objects, letting a media player change actions dynamically without if-else chains.
class State:
def play(self, player): pass
def pause(self, player): pass
def stop(self, player): pass
class PlayingState(State):
def play(self, player):
return "Already playing"
def pause(self, player):
player.state = PausedState()
return "Pausing playback"
def stop(self…
How to Use abstractmethod in Python
Define an abstract base class with abstract methods to enforce a common interface across subclasses.
import abc
class Shape(abc.ABC):
@abc.abstractmethod
def area(self):
"""Calculate area of the shape."""
@abc.abstractmethod
def perimeter(self):
"""Calculate perimeter of the shape."""
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
s…
How to implement a Facade class to simplify subsystem calls in Python
Use a Facade class to wrap complex subsystem interactions behind a simple start() method, hiding the details and providing a clean interface.
class CPU:
def freeze(self):
print("CPU: freezing")
def jump(self, position):
print(f"CPU: jumping to {position}")
def execute(self):
print("CPU: executing")
class Memory:
def load(self, position, data):
print(f"Memory: loading '{data}' at {position}")
class HardDr…
Implement the Strategy Pattern with Interchangeable Algorithm Classes in Python
Uses abstract base classes to define a SortStrategy interface, then swaps between BubbleSort and QuickSort at runtime.
from abc import ABC, abstractmethod
from typing import List
class SortStrategy(ABC):
@abstractmethod
def sort(self, data: List[int]) -> List[int]:
pass
class BubbleSort(SortStrategy):
def sort(self, data: List[int]) -> List[int]:
result = data[:]
n = len(result)
for i in…
Memento Pattern in Python: Save and Restore Object State
Implement the Memento design pattern to snapshot and restore an object's state, demonstrated with a text editor undo feature.
class TextEditor:
def __init__(self, text="", cursor_pos=0):
self.text = text
self.cursor_pos = cursor_pos
def type_text(self, new_text):
self.text += new_text
self.cursor_pos += len(new_text)
def move_cursor(self, pos):
self.cursor_pos = max(0, min(pos, len(self.t…
Observer Pattern in Python: Notify Listeners
Implement the Observer design pattern in Python with a Subject class that manages listeners and notifies them with messages.
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def notify(self, message):
for observer in self._observers:
observer.update(me…
Template Method Pattern in Python: Define Base Class with Algorithm Steps
Create a template method base class using ABC that defines the skeleton of an algorithm while letting subclasses implement specific steps.
from abc import ABC, abstractmethod
class DataProcessor(ABC):
"""Template method that defines the skeleton of an algorithm."""
def process(self):
"""Template method - defines the sequence of steps."""
self.load_data()
self.clean_data()
self.transform_data()
self.s…
Visitor Pattern in Python: Double Dispatch Demo
Demonstrates the Visitor design pattern with double dispatch so operations on Dog and Cat objects are selected at runtime without modifying their classes.
class Animal:
def accept(self, visitor):
visitor.visit(self)
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class SoundVisitor:
def visit(self, animal):
if isinstance(animal, Dog):
return self.visit_do…
Build a BFF (Backend for Frontend) Mock Aggregator in Python
A minimal HTTP server implementing the BFF pattern that aggregates user data and orders from two mock backends into a single JSON response.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
class MockBackendA:
def get_user(self, user_id):
return {"id": user_id, "name": "Alice", "service": "backend-a"}
class MockBackendB:
def get_orders(self, user_id):
return [
{…
Domain Driven Design Aggregate Root Example in Python
Model an Order as an aggregate root with invariants enforced through methods, demonstrating DDD principles in Python.
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Optional
from uuid import uuid4
class Money:
def __init__(self, amount: float, currency: str = "USD"):
self.amount = amount
self.currency = currency
def __add__(self, other: Money) -> Money:
…
Facade Pattern in Python with Mock Simplification
This code demonstrates the Facade pattern by hiding complex subsystem interactions behind a simple start/stop interface, and adds a MockFacade for testing failure scenarios.
class SubsystemA:
def operation_a(self):
return "Subsystem A: ready"
class SubsystemB:
def operation_b(self):
return "Subsystem B: ready"
class SubsystemC:
def operation_c(self):
return "Subsystem C: ready"
class Facade:
def __init__(self):
self._a = SubsystemA()
…
How to Apply the Clean Architecture Dependency Rule in Python
Demonstrates the dependency rule with a Protocol repository, a use case, and a presenter wired together at a composition root.
from dataclasses import dataclass
from typing import List, Protocol
class Repository(Protocol):
def get_items(self) -> List[str]:
...
@dataclass
class InMemoryRepository:
items: List[str]
def get_items(self) -> List[str]:
return self.items
class UseCase:
"""Application layer depends…
How to Build a Pipe and Filter Text Processing Chain in Python
A functional pipe-and-filter chain that transforms text through uppercase, whitespace normalization, number removal, stopword filtering, and file export.
import re
import sys
def pipe_filter_chain(stream):
def uppercase(text):
return text.upper()
def strip_whitespace(text):
return " ".join(text.split())
def remove_numbers(text):
return re.sub(r"\d+", "", text)
def remove_stopwords(text, stopwords={"the", "and", "of", "in"}):…
How to Build an Adapter to Translate External API Responses in Python
Build an adapter class that translates a mock external API's response shape into your internal representation, keeping callers decoupled from the external contract.
import json
from typing import Dict, Any
class ExternalAPI:
"""Mock external service returning a different data shape."""
def get_user(self, user_id: int) -> Dict[str, Any]:
return {
"id": user_id,
"full_name": "Jane Doe",
"email_address": "jane@example.com",
…
How to Implement the Abstract Factory Pattern in Python
Implements the Abstract Factory pattern to create families of related GUI objects (buttons, checkboxes) without specifying their concrete classes.
from abc import ABC, abstractmethod
class Button(ABC):
@abstractmethod
def render(self):
pass
class Checkbox(ABC):
@abstractmethod
def render(self):
pass
class WindowsButton(Button):
def render(self):
return "Rendering Windows-style button"
class WindowsCheckbox(Chec…
How to Implement the Flyweight Pattern in Python
Implements the Flyweight design pattern to share immutable intrinsic state (character + font) across many document objects, reducing memory usage.
class Character:
"""Flyweight - stores only intrinsic state (shared)."""
def __init__(self, char: str, font: str):
self.char = char
self.font = font
def render(self, size: int) -> str:
return f"{self.char}_{self.font}_{size}"
class CharacterFactory:
"""Flyweight factory - ma…
How to Implement the Strategy Pattern in Python
This Python code demonstrates the Strategy design pattern using interchangeable sorting algorithms (bubble sort and quick sort) that can be swapped at runtime.
class SortingStrategy:
def sort(self, data):
raise NotImplementedError
class BubbleSort(SortingStrategy):
def sort(self, data):
result = data.copy()
n = len(result)
for i in range(n):
for j in range(0, n - i - 1):
if result[j] > result[j + 1]:
…
How to Migrate a Legacy Facade with the Strangler Fig Pattern in Python
Use a facade to wrap a legacy API and incrementally migrate callers to a modern interface, following the strangler fig pattern.
class LegacyAPI:
"""Simulates the legacy system's raw interface."""
def get_user(self, user_id):
return {"id": user_id, "name": "Alice", "legacy": True}
class UserService:
"""Facade that wraps the legacy system with a modern interface."""
def __init__(self, legacy_api=None):
self.lega…
How to Structure a Three-Tier Layered Architecture in Python
A mock three-tier architecture with presentation, business, and data layers that process a user request from input to response.
class PresentationLayer:
def __init__(self, business_layer):
self.business = business_layer
def handle_request(self, user_id):
print(f"[Presentation] Received request for user {user_id}")
data = self.business.process_user(user_id)
print(f"[Presentation] Response: {data}")
…
Lazy loading with a proxy in Python: defer expensive service creation
A lazy proxy defers creating an expensive service object until its method is first called, then caches it for reuse.
import time
import random
class ExpensiveService:
def __init__(self, name):
self.name = name
print(f"Creating expensive service: {self.name}")
def fetch_data(self):
time.sleep(1)
return f"Data from {self.name}: {random.randint(1, 100)}"
class LazyProxy:
def __init__(sel…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.