Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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…
Composition over Inheritance: How to Build a Wallet Account in Python
Demonstrates composition by wrapping a WalletAccount class in an AuditedWallet decorator-like class to add behavior without changing the original class.
class WalletAccount:
def __init__(self, owner, balance=0.0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
return self.balance
def withdraw(self, …
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…
Python Factory Method: Create Shapes by Type String
A factory method that maps a type string to a concrete shape class and returns an instance, with runtime error handling.
class Shape:
def draw(self):
raise NotImplementedError
class Circle(Shape):
def draw(self):
return "Drawing a circle"
class Square(Shape):
def draw(self):
return "Drawing a square"
class Triangle(Shape):
def draw(self):
return "Drawing a triangle"
class ShapeFact…
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…
Dependency Injection in Python for Testability
Inject a config dependency into a service so you can swap a real environment-based config for a fake one in tests.
import os
class Config:
"""Simple config loader that can be easily faked in tests."""
def get(self, key, default=None):
return os.environ.get(key, default)
class UserService:
def __init__(self, config):
self.config = config
def get_timeout(self):
return int(self.config.get(…
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 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 Build an MVP Presenter View Mock in Python
A minimal MVP (Model-View-Presenter) mock showing a Presenter controlling a SlideDeck model with slide navigation and typed state via dataclasses.
from dataclasses import dataclass, field
from typing import List
@dataclass
class SlideDeck:
title: str
slides: List[str] = field(default_factory=list)
current_index: int = 0
def next_slide(self) -> str:
if self.current_index < len(self.slides) - 1:
self.current_index += 1
…
How to Implement a Data Helper Class in Python
Build a beginner-friendly DataHelper class using dataclasses and key system design patterns like Command, Strategy, and Map.
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
@dataclass
class DataHelper:
"""A beginner-friendly data utility with common system design patterns."""
data: List[Dict[str, Any]] = field(default_factory=list)
def add_record(self, r…
How to Implement a Factory Method by Type String in Python
A factory method maps a type string to a class, creating and returning the appropriate object instance while handling unknown types gracefully.
class Animal:
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class AnimalFactory:
@staticmethod
def create(animal_type: str) -> Animal:
animal_types = {
…
How to Implement a Simple Event Bus in Python
Create a publish-subscribe event bus using dataclasses and defaultdict to decouple event producers from consumers.
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Callable, Dict, List, Set
@dataclass
class EventBus:
_subscribers: Dict[str, List[Callable]] = field(
default_factory=lambda: defaultdict(list)
)
def subscribe(self, event_type: str, handler: Callable…
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 Prototype Pattern with Deep Copy in Python
Implements the Prototype design pattern using copy.deepcopy to clone complex objects without sharing mutable state.
import copy
from dataclasses import dataclass, field
from typing import List
@dataclass
class Engine:
horsepower: int
@dataclass
class Car:
brand: str
engine: Engine
accessories: List[str] = field(default_factory=list)
def clone_prototype(car: Car) -> Car:
return copy.deepcopy(car)
if __name__ …
How to Implement the Repository Pattern in Python with an In-Memory Dict
Stores, retrieves, updates, and deletes user records in memory using a Repository abstraction over a plain dict, isolating data access from business logic.
class UserRepository:
def __init__(self):
self._storage = {}
self._next_id = 1
def create(self, name, email):
user_id = self._next_id
self._next_id += 1
self._storage[user_id] = {"id": user_id, "name": name, "email": email}
return self._storage[user_id]
def…
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…
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.