Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

12 matches
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:
           …
16 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…
13 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…
12 0 Open
OOP & classes medium

How to Lazy Load an Expensive Attribute with a Proxy in Python

This code shows a Proxy class that lazily loads an ExpensiveResource only when first accessed, caching it for subsequent uses.

lazy-loading proxy properties
Python
class ExpensiveResource:
    def __init__(self, name):
        self.name = name
        print(f"Expensive resource '{name}' created (e.g., DB connection)")

    def use(self):
        return f"Using {self.name}"

class Proxy:
    def __init__(self, name):
        self._name = name
        self._resource = None

    @p…
15 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…
14 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…
12 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…
11 0 Open
System design patterns medium

How to Implement CQRS with Separate Read and Write Models in Python

Implements Command Query Responsibility Segregation (CQRS) by splitting data into separate write and read models with dedicated repositories, using dataclasses for structure.

cqrs dataclasses repositories
Python
from dataclasses import dataclass, field
from typing import List, Dict, Optional


@dataclass
class OrderWriteModel:
    order_id: int
    customer: str
    items: List[str] = field(default_factory=list)

    def add_item(self, item: str) -> None:
        self.items.append(item)


@dataclass
class OrderReadModel:
    …
14 0 Open
System design patterns medium

How to Implement a Simple MVVM Binding Mock in Python

A minimal Python implementation of the MVVM pattern, mocking data binding so views auto-update when the view model changes.

mvvm binding observer pattern
Python
class BindingMock:
    def __init__(self, view_model):
        self.view_model = view_model
        self.subscribers = []

    def bind(self, property_name, callback):
        self.subscribers.append((property_name, callback))

    def set(self, property_name, value):
        setattr(self.view_model, property_name, va…
18 0 Open
System design patterns medium

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.

flyweight design-patterns memory-optimization
Python
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…
15 0 Open
System design patterns medium

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.

design-pattern strategy oop
Python
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]:
      …
13 0 Open
System design patterns medium

Template Method Workflow Steps Base Class in Python

Define a reusable workflow skeleton in a base class and let subclasses fill in each step with the Template Method design pattern.

template-method design-patterns abc
Python
from abc import ABC, abstractmethod


class DataPipeline(ABC):
    """Template Method pattern: defines a workflow skeleton."""

    def run(self):
        """Template method - defines the algorithm's structure."""
        result = {"extracted": False, "transformed": False, "loaded": False}
        raw_data = self._ext…
13 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.