Reference library

Python Code Samples

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

57 matches
AI & LLM integration patterns easy

JSON Mode Prompt Schema Output in Python

Extract a user object to JSON with explicit schema keys, ready for LLM JSON-mode prompts.

json schema llm
Python
import json
from typing import Any, Dict


def extract_user_as_json(user: Dict[str, Any]) -> str:
    """Extract a user object and return it as JSON using explicit schema keys."""
    schema_fields = ("id", "name", "email", "is_active")
    user_subset = {key: user[key] for key in schema_fields if key in user}
    ret…
13 0 Open
AI & LLM integration patterns easy

Serialize and Format Data for LLM Prompts in Python

Use dataclasses and the json module to convert Python objects to JSON strings, parse them back, and format structured data into prompt-friendly text for LLM calls.

dataclasses json llm
Python
import json
from dataclasses import dataclass, asdict


@dataclass
class Recipe:
    """Simple data model to represent a recipe."""
    name: str
    cuisine: str
    prep_minutes: int


def to_json(recipe: Recipe) -> str:
    """Serialize a Recipe to a JSON string."""
    return json.dumps(asdict(recipe), indent=2)

…
14 0 Open
Data pipelines & processing medium

Normalize Timestamps to UTC DateTime in Python

Convert timestamps in multiple formats to UTC-aware datetime objects using datetime.strptime and astimezone.

datetime timezone utc
Python
from datetime import datetime, timezone

raw_timestamps = [
    "2024-01-15 14:30:00+02:00",
    "17/05/2024 09:15:00 -0500",
    "2024-03-01T22:45:00Z",
    "2024-06-20 08:00:00+09:30"
]

def parse_and_convert(ts: str) -> datetime:
    normalized_ts = ts.strip().replace("Z", "+00:00")
    formats = [
        "%Y-%m-%…
14 0 Open
Git + Python easy

How to Make a Shallow Clone of an Object in Python

Demonstrates using copy.copy() to create a shallow clone of a Python object, showing how nested mutable data is shared while top-level attributes are independent.

copy shallow-copy clone
Python
import copy


class Config:
    def __init__(self):
        self.settings = {"volume": 50}
        self.user = "admin"


def demonstrate_shallow_copy():
    original = Config()
    shallow = copy.copy(original)

    # Mutating nested object is visible in both (shallow copy share it)
    shallow.settings["volume"] = 90…
14 0 Open
Cloud + Python easy

Create a Cloud Storage Helper Class in Python

Build a simple local file-based helper class that mimics cloud storage operations like save, load, and list JSON objects.

cloud-storage json file-io
Python
import datetime
import json
from pathlib import Path


class CloudDataHelper:
    """Simple helper for reading/writing JSON files in a cloud-style folder."""

    def __init__(self, base_dir: str = "cloud_storage"):
        self.base_dir = Path(base_dir)
        self.base_dir.mkdir(exist_ok=True)

    def save_json(se…
15 0 Open
Cloud + Python medium

How to mock boto3 S3 upload file wrapper in Python

Wrap an S3 put_object call in a testable function that returns metadata, and mock boto3 to verify the upload without touching AWS.

boto3 s3 aws
Python
import boto3
import io


def upload_file_to_s3(file_obj, bucket, key, object_metadata=None):
    """Upload a file-like object to S3 and return a metadata dict."""
    s3 = boto3.client("s3")
    content = file_obj.read()
    s3.put_object(
        Bucket=bucket,
        Key=key,
        Body=content,
        Metadata=…
13 0 Open
Cloud + Python easy

Mock Lambda handler event context dict in Python

Simulates an AWS Lambda invocation by passing a mock event dict and context object to a handler, then prints the response.

lambda aws mock
Python
import json


def lambda_handler(event, context):
    """
    A mock AWS Lambda handler that processes an event dict and context object.
    Demonstrates the typical Lambda function signature and basic event/context usage.
    """
    print("Received event:", json.dumps(event, indent=2))
    print("Function name:", co…
14 0 Open
Cloud + Python medium

Mock S3 List Objects Paginator in Python

This code implements a mock S3 paginator that yields pages of object keys, mimicking the behavior of boto3's list_objects_v2 paginator for local testing.

s3 mock paginator
Python
import json
from datetime import datetime, timezone


class MockS3Paginator:
    """A mock S3 list_objects_v2 paginator returning pages of keys."""

    def __init__(self, bucket, all_keys, page_size=1000):
        self.bucket = bucket
        self.all_keys = all_keys
        self.page_size = page_size

    def pagina…
13 0 Open
Concurrency & performance medium

How to Use a Weakref Cache to Avoid Memory Leaks in Python

This code demonstrates building a value cache with weakref.WeakValueDictionary so objects can be garbage collected when no longer referenced, preventing memory leaks.

weakref caching memory
Python
import weakref
import gc


class ExpensiveObject:
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return f"ExpensiveObject('{self.name}')"


class ObjectCache:
    def __init__(self):
        self._cache = weakref.WeakValueDictionary()

    def get_or_create(self, name):
       …
13 0 Open
Testing & modern typing medium

How to Mock an Object Method in Python unittest

Mock a method on an instance or class with @patch.object, set its return value, and assert its call arguments in Python unittest.

unittest mock patch
Python
import unittest
from unittest.mock import patch

class Calculator:
    def add(self, a, b):
        return a + b
    
    def multiply(self, a, b):
        return a * b

class TestCalculator(unittest.TestCase):
    def test_add_normal(self):
        calc = Calculator()
        result = calc.add(2, 3)
        self.asse…
14 0 Open
Testing & modern typing easy

How to Use TypedDict and Dataclasses in Python

Create typed data structures with TypedDict and dataclasses, then use them as helper functions for describing objects in a type-safe way.

typing typdict dataclass
Python
from typing import TypedDict, NotRequired, Optional
from dataclasses import dataclass


class User(TypedDict):
    name: str
    age: NotRequired[int]
    email: Optional[str]


@dataclass
class Product:
    id: int
    title: str
    price: float = 0.0


def describe_user(user: User) -> str:
    age = user.get("age",…
12 0 Open
System design patterns easy

Builder pattern for mocking complex objects in Python

Use a fluent Builder to construct realistic mock objects with defaults, enabling readable test data setup.

builder-pattern mock-data testing
Python
class User:
    def __init__(self):
        self.name = "default"
        self.age = 0
        self.email = "unknown@example.com"
        self.address = "unknown"

    def __repr__(self):
        return f"User(name={self.name!r}, age={self.age}, email={self.email!r}, address={self.address!r})"


class UserBuilder:
   …
15 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

How to Build a Sidecar Logging Proxy in Python

Wrap any object with a proxy that transparently logs every method call, arguments, return value, and execution time to a file — mimicking a sidecar pattern.

proxy logging sidecar
Python
import logging
import time
from datetime import datetime


class LoggingProxy:
    """Sidecar-style proxy that logs all calls to a wrapped object."""

    def __init__(self, target, log_file="proxy.log"):
        self._target = target
        logging.basicConfig(
            filename=log_file,
            level=loggin…
15 0 Open
System design patterns medium

How to Build an Anti-Corruption Layer in Python

Wrap a legacy system with a translation layer that converts awkward legacy data into a clean, modern DTO (Data Transfer Object) for use by new code.

anti-corruption-layer ddd dto
Python
class LegacyOrderSystem:
    """Legacy system with awkward, unstructured data."""
    def get_order(self):
        return {
            "order_id": "ORD-123",
            "cust": "Acme Corp",
            "items": [{"sku": "A1", "qty": 2, "price_each": 10.0}],
            "ship_to": "123 Main St, Springfield"
        }…
15 0 Open
System design patterns medium

How to Build an Immutable Money Value Object in Python

Implement an immutable Money class with rounded decimal amounts, currency, safe equality, and hashing for use as a value object.

value-object immutability money
Python
class Money:
    def __init__(self, amount: float, currency: str):
        object.__setattr__(self, "_amount", round(amount, 2))
        object.__setattr__(self, "_currency", currency)

    def __setattr__(self, name, value):
        raise AttributeError(f"Money is immutable: cannot set '{name}'")

    def __delattr__…
13 0 Open
System design patterns easy

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.

factory-pattern design-patterns oop
Python
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 = {
          …
14 0 Open
System design patterns medium

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.

abstract-factory design-patterns system-design
Python
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…
13 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 easy

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.

prototype-pattern deepcopy dataclasses
Python
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__ …
13 0 Open
System design patterns medium

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.

proxy lazy-loading design-patterns
Python
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…
15 0 Open
System design patterns medium

Object Pool Pattern for Database Connections in Python

Implements a reusable connection pool with acquire/release and context manager support, mocking database connections with idle reuse and exhaustion handling.

object-pool connection-pool databases
Python
import time
from contextlib import contextmanager
from collections import deque


class ConnectionPool:
    def __init__(self, size=3, max_idle=5):
        self._idle = deque(maxlen=max_idle)
        self._active = set()
        self.size = size

    def _create(self):
        return {"created_at": time.time(), "queri…
12 0 Open
API design & gRPC medium

How to Validate Request Body JSON Against a Schema in Python

Build a lightweight schema validator to check required fields, types, string lengths, allowed values, and nested objects in a JSON request body.

api-validation json schema-validation
Python
import json


def validate_against_schema(data, schema, path=""):
    errors = []

    if not isinstance(data, dict):
        errors.append(f"{path}: expected object, got {type(data).__name__}")
        return errors

    for field, rules in schema.items():
        field_path = f"{path}.{field}" if path else field

  …
15 0 Open
API design & gRPC easy

Sort Python list by query param order_by

Sort a list of dataclass objects dynamically by a field name passed as a query param, with asc/desc direction support.

sorting dataclasses api
Python
from dataclasses import dataclass


@dataclass
class Item:
    name: str
    price: int


def sort_items(items, order_by, direction="asc"):
    if order_by not in ("name", "price"):
        raise ValueError(f"Unsupported sort field: {order_by}")

    reverse = direction.lower() == "desc"
    return sorted(items, key=l…
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.