Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

47 matches
Functions & basics easy

How to Use a Dispatch Table in Python (Map Strings to Functions)

Maps string command names to callable functions in a dictionary, then dispatches calls safely with error handling.

dispatch-table dictionary functions
Python
def add(a, b):
    return a + b


def subtract(a, b):
    return a - b


def multiply(a, b):
    return a * b


def divide(a, b):
    if b == 0:
        raise ValueError("Division by zero")
    return a / b


dispatch = {
    "add": add,
    "subtract": subtract,
    "multiply": multiply,
    "divide": divide,
}


def…
13 0 Open
OOP & classes medium

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

borg monostate shared-state
Python
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…
14 0 Open
OOP & classes medium

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.

bridge design-pattern oop
Python
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:
           …
15 0 Open
OOP & classes medium

Composable Predicates with the &, |, ~ Operators in Python

Define a reusable Predicate class that combines boolean checks with & (AND), | (OR), and ~ (NOT) operators.

predicates operator-overloading oop
Python
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…
13 0 Open
OOP & classes easy

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.

composition design-patterns oop
Python
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, …
13 0 Open
OOP & classes easy

How to Build a Fluent Interface with the Builder Pattern in Python

Learn to implement a fluent builder pattern in Python by chaining methods that return self, enabling readable object construction.

builder fluent oop
Python
class Pizza:
    def __init__(self):
        self.size = None
        self.toppings = []
        self.crust = None

    def set_size(self, size):
        self.size = size
        return self

    def add_topping(self, topping):
        self.toppings.append(topping)
        return self

    def set_crust(self, crust):
…
14 0 Open
OOP & classes easy

How to Implement a Singleton Class in Python

This code demonstrates a classic Singleton pattern in Python by overriding __new__ to ensure only one instance of the class is created, even when instantiated multiple times.

singleton class oop
Python
class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        self.value = 0


if __name__ == "__main__":
    s1 = Singleton()
    s2 = Singleton()
    s1.value = 42
    print…
14 0 Open
OOP & classes medium

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.

command-pattern design-patterns oop
Python
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…
12 0 Open
OOP & classes medium

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.

state-pattern design-patterns oop
Python
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…
11 0 Open
OOP & classes medium

How to Use abstractmethod in Python

Define an abstract base class with abstract methods to enforce a common interface across subclasses.

oop abstract abc
Python
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…
9 0 Open
OOP & classes medium

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.

facade design-patterns oop
Python
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…
14 0 Open
OOP & classes medium

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.

strategy-pattern oop abstract-class
Python
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…
11 0 Open
OOP & classes medium

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.

memento design-pattern undo
Python
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…
13 0 Open
OOP & classes medium

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.

design-pattern observer oop
Python
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…
11 0 Open
OOP & classes easy

Python Adapter Class: Wrap Legacy Interface

Convert a legacy system's interface into a modern one using the Adapter pattern in Python, translating method calls and data formats.

adapter design-pattern oop
Python
class LegacySystem:
    """Legacy interface - old method names and parameter format."""
    def query_employee_info(self, emp_id, emp_name):
        return f"Legacy: {emp_id} - {emp_name}"

    def update_employee_department(self, emp_id, department_code):
        return f"Legacy: Updated {emp_id} to dept {department_…
12 0 Open
OOP & classes easy

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.

factory-pattern oop polymorphism
Python
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…
11 0 Open
OOP & classes medium

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.

template-method abstract-class design-pattern
Python
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…
11 0 Open
OOP & classes medium

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.

visitor-pattern design-patterns double-dispatch
Python
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…
10 0 Open
Testing & modern typing easy

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.

dependency-injection testing mocking
Python
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(…
15 0 Open
System design patterns medium

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.

bff http-server aggregation
Python
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 [
            {…
17 0 Open
System design patterns medium

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.

ddd aggregate-root object-oriented
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:
       …
12 0 Open
System design patterns medium

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.

facade-pattern design-patterns abstraction
Python
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()
   …
15 0 Open
System design patterns medium

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.

clean-architecture dependency-inversion protocol
Python
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…
12 0 Open
System design patterns medium

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.

pipeline text-processing functional
Python
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"}):…
14 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.