Reference library

Python Code Samples

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

86 matches
Errors & debugging medium

Collect Multiple Validation Errors in Python Before Raising

A chainable Validator class that accumulates all validation errors and raises them together in a single exception.

validation exceptions errors
Python
class ValidationError(Exception):
    pass

class Validator:
    def __init__(self):
        self.errors = []
    
    def validate_required(self, value, field_name):
        if not value:
            self.errors.append(f"{field_name} is required")
        return self
    
    def validate_email(self, email):
        …
14 0 Open
Errors & debugging medium

Implement circuit breaker open after failures demo in Python

A minimal CircuitBreaker class that calls a function and automatically 'opens' after a set number of consecutive failures, blocking further calls with a RuntimeError.

circuit-breaker resilience error-handling
Python
import time
from datetime import datetime


class CircuitBreaker:
    def __init__(self, threshold=3):
        self.threshold = threshold
        self.failure_count = 0
        self.is_open = False

    def call(self, func, *args, **kwargs):
        if self.is_open:
            raise RuntimeError("Circuit is OPEN")
  …
13 0 Open
Files & data medium

Build a Personal Work Hours Tracker in Python

A Python class that logs daily work hours to a CSV file and produces a weekly summary of total hours worked.

work-hours time-tracking csv
Python
import csv
from pathlib import Path
from datetime import datetime, date

class WorkHoursTracker:
    def __init__(self, file_path="work_hours.csv"):
        self.file_path = Path(file_path)
        if not self.file_path.exists():
            with open(self.file_path, "w", newline="") as f:
                writer = csv…
60 0 Open
Files & data medium

Build a Secure Local Password Vault with Encrypted Storage in Python

A Python class that stores and retrieves passwords in an encrypted JSON file using Fernet symmetric encryption from the cryptography library.

encryption security passwords
Python
import json
import os
import base64
import hashlib
from cryptography.fernet import Fernet
from getpass import getpass

class PasswordVault:
    def __init__(self, vault_file="vault.json", key_file="vault.key"):
        self.vault_file = vault_file
        self.key_file = key_file
        self.key = self._load_or_creat…
50 0 Open
Files & data medium

How to Load Pickle Files Safely in Python

This code demonstrates how to load pickle files safely in Python by using a restricted unpickler that only allows specific, trusted classes, preventing arbitrary code execution from untrusted pickles.

pickle security serialization
Python
import pickle

# Default pickle.load is unsafe: it executes arbitrary code when unpickling.
class Unsafe:
    def __reduce__(self):
        return (eval, ("open('/tmp/pickle_demo.txt', 'w').write('pwned')",))

# Create a malicious payload (simulating untrusted source)
malicious_data = pickle.dumps(Unsafe())

# Safe ap…
14 0 Open
Dictionaries & sets medium

Build a Case-Insensitive Dict with a Wrapper Class in Python

Create a custom dict subclass that treats keys as case-insensitive by normalizing them to lowercase, with a full set of common dict methods.

dictionary case-insensitive wrapper
Python
class CaseInsensitiveDict:
    def __init__(self, data=None):
        self._data = {}
        if data:
            self.update(data)

    def __setitem__(self, key, value):
        self._data[str(key).lower()] = value

    def __getitem__(self, key):
        return self._data[str(key).lower()]

    def __delitem__(sel…
13 0 Open
Dictionaries & sets medium

How to Build a TTL Cache Dict in Python

Create a dictionary subclass that automatically expires keys after a fixed time-to-live using timestamps.

dictionary cache ttl
Python
import time

class TTLDict(dict):
    def __init__(self, ttl, *args, **kwargs):
        self.ttl = ttl
        self._expires = {}
        super().__init__(*args, **kwargs)

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self._expires[key] = time.time() + self.ttl

    def __geti…
16 0 Open
Dictionaries & sets medium

How to Build a Two-Way Dictionary in Python

Implement a BiDict class that supports both forward key-to-value and reverse value-to-key lookups with a simple add, delete, and update API.

dictionary bidirectional class
Python
class BiDict:
    def __init__(self, data=None):
        self.forward = {}
        self.backward = {}
        if data:
            self.update(data)

    def update(self, data):
        for key, value in data.items():
            self[key] = value

    def __setitem__(self, key, value):
        self.forward[key] = val…
11 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…
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…
14 0 Open
OOP & classes medium

How to Build a Linked List Node Class in Python

Create a Node class and a LinkedList class with insert, remove, and display methods to manage a singly linked list.

linked-list node oop
Python
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def insert(self, data):
        new_node = Node(data)
        if not self.head:
            self.head = new_node
        else:
            current = self.…
12 0 Open
OOP & classes medium

How to Create a Data Splitter Class in Python

This code defines a DataSplitter class that splits data by index, into chunks, or by a predicate, demonstrating OOP principles in Python.

class data-splitting slicing
Python
class DataSplitter:
    def __init__(self, data):
        self.data = list(data)
    
    def split_by_index(self, index):
        return self.data[:index], self.data[index:]
    
    def split_into_chunks(self, chunk_size):
        return [self.data[i:i + chunk_size] for i in range(0, len(self.data), chunk_size)]
   …
14 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

How to Use __slots__ in Python Classes for Memory Efficiency

Defines classes with __slots__ to prevent dynamic attribute creation and reduce memory usage, including inheritance with additional slots.

slots oop memory
Python
```python
class Person:
    __slots__ = ("name", "age")

    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

    def greet(self) -> str:
        return f"Hi, I'm {self.name} and I'm {self.age} years old."


class Employee(Person):
    __slots__ = ("role",)

    def __init__(se…
13 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…
10 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…
15 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…
12 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

Python Abstract Class with Concrete Subclasses

Define an abstract base class with abstract methods and implement them in concrete subclasses like Rectangle and Circle.

abc abstract-methods oop
Python
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

    @abstractmethod
    def perimeter(self):
        pass

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        ret…
14 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…
12 0 Open
OOP & classes medium

Understanding Multiple Inheritance Method Resolution Order in Python

This code demonstrates how Python's MRO determines which greet method is called in a diamond inheritance scenario, and prints the full MRO for class D.

multiple inheritance mro inheritance
Python
class A:
    def greet(self):
        return "Hello from A"

class B(A):
    def greet(self):
        return "Hello from B"

class C(A):
    def greet(self):
        return "Hello from C"

class D(B, C):
    pass


if __name__ == "__main__":
    d = D()
    print(d.greet())
    print(D.__mro__)
12 0 Open
OOP & classes medium

Unit of Work Pattern: Track Changes, Commit, and Rollback in Python

This code defines a UnitOfWork class that tracks operations (add) and supports commit to apply changes and rollback to revert them, using a dataclass-based logger.

unit-of-work dataclass transaction
Python
from dataclasses import dataclass, field
from typing import Any, Callable, List, Tuple


@dataclass
class UnitOfWork:
    log: List[Tuple[str, Callable, tuple, dict]] = field(default_factory=list)

    def track(self, operation: str, fn: Callable, *args, **kwargs):
        self.log.append((operation, fn, args, kwargs)…
13 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

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.