Reference library

Python Code Samples

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

56 matches
Errors & debugging easy

How to Dump a Debugging Repr for Unknown Types in Python

Build a fallback repr that shows dataclass fields or object attributes for any value, handy when debugging unknown types.

debugging repr dataclasses
Python
import dataclasses
from typing import Any


@dataclasses.dataclass
class Sample:
    name: str
    values: list[int]


def dump_repr(obj: Any) -> str:
    """Return a concise but complete repr for debugging unknown types."""
    if dataclasses.is_dataclass(obj):
        fields = ", ".join(
            f"{field.name}={…
12 0 Open
Errors & debugging easy

How to Emit Deprecation Warnings in Python

Use the warnings module to mark legacy classes and methods as deprecated, letting users know to switch to newer APIs.

warnings deprecation debugging
Python
import warnings


class OldAPI:
    def __init__(self):
        warnings.warn(
            "OldAPI is deprecated; use NewAPI instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        self.data = []

    def add(self, item):
        warnings.warn(
            "OldAPI.add() is deprecated; us…
14 0 Open
Errors & debugging easy

How to define an exception hierarchy for domain errors in Python

Create a custom exception hierarchy with a base DomainError class and specific subclasses to handle validation, not-found, permission, and concurrency errors cleanly in Python apps.

exceptions domain-errors error-handling
Python
class DomainError(Exception):
    """Base class for all domain errors."""
    pass

class ValidationError(DomainError):
    """Raised when input data fails validation rules."""
    pass

class NotFoundError(DomainError):
    """Raised when a requested entity does not exist."""
    pass

class PermissionDeniedError(Dom…
14 0 Open
OOP & classes easy

Compute Derived Fields with @dataclass __post_init__ in Python

Compute derived fields like distance, area, and perimeter automatically in Python dataclasses using __post_init__ and field(init=False).

dataclasses oop derived-fields
Python
from dataclasses import dataclass, field
from math import sqrt


@dataclass
class Point:
    x: float
    y: float
    distance: float = field(init=False)

    def __post_init__(self):
        self.distance = sqrt(self.x ** 2 + self.y ** 2)


@dataclass
class Rectangle:
    width: float
    height: float
    area: flo…
12 0 Open
OOP & classes easy

Design a Data Helper Class in Python

Create a simple Object-Oriented data helper with DataPoint and Dataset classes that store, describe, and summarize coordinate points.

oop classes data-helper
Python
class DataPoint:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.label = None

    def describe(self):
        """Return a human-readable description of the data point."""
        base = f"DataPoint(x={self.x}, y={self.y})"
        return f"{base}, label='{self.label}'" if self.label e…
15 0 Open
OOP & classes easy

How to Build a Data Helper Class in Python with OOP

Create a beginner-friendly Python class that loads CSV data, filters records by field, and counts entries using object-oriented programming.

oop csv data
Python
class DataHelper:
    """A beginner-friendly OOP helper for handling simple datasets."""
    
    def __init__(self, filename):
        self.filename = filename
        self.data = self._load_data()
    
    def _load_data(self):
        """Load data from a CSV file into a list of dictionaries."""
        import csv
 …
12 0 Open
OOP & classes easy

How to Call a Parent Class __init__ with super() in Python

Shows how to chain __init__ calls through a class hierarchy using super(), so each class sets its own attributes while reusing the parent's initialization logic.

oop inheritance super
Python
class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species
        print(f"Animal init: {self.name}, {self.species}")

class Mammal(Animal):
    def __init__(self, name, species, fur_color):
        super().__init__(name, species)
        self.fur_color = fur_color
   …
13 0 Open
OOP & classes easy

How to Compare Dataclass Instances by Specific Fields in Python

Use @dataclass(order=True) with field(compare=False) to control which fields determine ordering and equality between instances.

dataclasses comparison sorting
Python
from dataclasses import dataclass, field
from typing import Any

@dataclass(order=True)
class Person:
    name: str = field(compare=False)
    age: int
    height_cm: float
    priority: int = field(compare=False, default=0)

    def __repr__(self):
        return f"Person(name={self.name!r}, age={self.age}, height={s…
14 0 Open
OOP & classes easy

How to Convert Data Types in Python with a Helper Class

This code defines a beginner-friendly OOP helper class for common data conversions like string to list, list to dict, JSON string, and CSV row, with an advanced subclass for numeric casting.

oop classes data-conversion
Python
class DataConverter:
    """A beginner-friendly helper class for common data conversions."""
    
    def __init__(self, data):
        self.data = data
    
    def to_list(self):
        """Convert string data (comma-separated) to a list."""
        if isinstance(self.data, str):
            return [item.strip() for…
14 0 Open
OOP & classes easy

How to Count Items in a Python Class

A beginner-friendly Inventory class that stores item quantities in a dictionary and provides add, remove, count, and summary methods.

oop classes inventory
Python
class Inventory:
    def __init__(self):
        self.items = {}

    def add(self, item, quantity=1):
        self.items[item] = self.items.get(item, 0) + quantity

    def remove(self, item, quantity=1):
        if item not in self.items:
            raise ValueError(f"{item} not in inventory")
        self.items[it…
13 0 Open
OOP & classes easy

How to Create Immutable Data Classes with frozen=True in Python

Create immutable data classes in Python using @dataclass(frozen=True) to prevent attribute modifications after instantiation.

dataclass frozen immutable
Python
from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: float
    y: float

    def distance_from_origin(self) -> float:
        return (self.x**2 + self.y**2) ** 0.5

if __name__ == "__main__":
    p = Point(3.0, 4.0)
    print(p)
    print(f"Distance from origin: {p.distance_from_origin():.2f}…
13 0 Open
OOP & classes easy

How to Create a Data Helper Class in Python with OOP

A complete OOP example with User, Post, and Blog classes that manage data relationships and provide clear helper methods.

oop classes data-modeling
Python
class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.posts = []

    def create_post(self, title, content):
        post = Post(title, content, self)
        self.posts.append(post)
        return post

    def get_post_count(self):
        return len(self.p…
12 0 Open
OOP & classes easy

How to Create an Immutable Money Class in Python with dataclasses

Define a frozen dataclass Money that holds an amount and currency, enforces non-negative amounts, and supports safe addition across matching currencies.

dataclass immutable money
Python
from dataclasses import dataclass


@dataclass(frozen=True)
class Money:
    amount: float
    currency: str = "USD"

    def __post_init__(self) -> None:
        if self.amount < 0:
            raise ValueError("amount must be non-negative")

    def add(self, other: "Money") -> "Money":
        if self.currency != o…
16 0 Open
OOP & classes easy

How to Create an Iterable Class with __iter__ and __next__ in Python

Build custom iterable classes in Python by implementing the __iter__ and __next__ dunder methods to yield items on demand.

iterable iterator dunder-methods
Python
class EvenNumbers:
    def __init__(self, limit):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.limit:
            raise StopIteration
        result = self.current
        self.current += 2
        return resul…
14 0 Open
OOP & classes easy

How to Define Dataclass Field Defaults in Python

Implement a Python dataclass with default values for simple fields and default factories for mutable collections.

dataclasses oop defaults
Python
from dataclasses import dataclass, field
from typing import List

@dataclass
class Product:
    name: str
    price: float = 0.0
    quantity: int = 0
    tags: List[str] = field(default_factory=list)
    metadata: dict = field(default_factory=dict)

if __name__ == "__main__":
    p1 = Product("Laptop", 999.99, 5)
   …
13 0 Open
OOP & classes easy

How to Define a Simple Python Class with __init__ and __repr__

Define a basic Python class with an __init__ method to set instance attributes and a __repr__ method for a readable representation of objects.

classes oop init
Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

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


if __name__ == "__main__":
    person = Person("Alice", 30)
    print(person)
15 0 Open
OOP & classes easy

How to Implement Rich Comparison Ordering in Python Classes

This code demonstrates how to implement rich comparison operators (like <, <=, >, >=, ==, !=) in a Python class by defining __lt__ and __eq__, enabling sorting and ordering of custom objects.

rich comparison sorting operators
Python
class Task:
    def __init__(self, priority, name):
        self.priority = priority
        self.name = name

    def __lt__(self, other):
        if not isinstance(other, Task):
            return NotImplemented
        return self.priority < other.priority

    def __eq__(self, other):
        if not isinstance(oth…
12 0 Open
OOP & classes easy

How to define a custom exception class in Python with an error code attribute

Create a custom exception class with extra attributes like an error code, then raise and catch it in a try/except block.

exceptions classes error-handling
Python
class UserNotFoundError(Exception):
    def __init__(self, user_id, error_code=404):
        self.user_id = user_id
        self.error_code = error_code
        super().__init__(f"User with ID {user_id} was not found (error code: {error_code})")

def find_user(user_id, users_db):
    if user_id not in users_db:
      …
15 0 Open
OOP & classes easy

How to merge dictionaries by a key in Python with a class

This code defines a DataMerger class that collects dictionary records and merges them by a specified key, combining fields from multiple records with the same key.

classes dictionaries merging
Python
class DataMerger:
    def __init__(self):
        self.records = []

    def add_record(self, record):
        if isinstance(record, dict):
            self.records.append(record)
        else:
            raise TypeError("Record must be a dictionary")

    def merge_by_key(self, key):
        merged = {}
        for …
13 0 Open
OOP & classes easy

Parse CSV Data with a Python Class

Encapsulate CSV file loading and column/row access methods in a reusable DataParser class for beginners.

oop csv parsing
Python
class DataParser:
    def __init__(self, file_path):
        self.file_path = file_path
        self.data = []

    def load_data(self):
        with open(self.file_path, 'r') as file:
            for line in file:
                row = line.strip().split(',')
                self.data.append(row)
        return self.…
12 0 Open
OOP & classes easy

Validate dataclass fields with __post_init__ in Python

Add custom validation to a Python dataclass inside __post_init__, raising ValueError or TypeError for invalid field values.

dataclasses validation post-init
Python
from dataclasses import dataclass, field
from typing import Optional


@dataclass
class Product:
    name: str
    price: float
    quantity: int = 1
    category: Optional[str] = None

    def __post_init__(self):
        if not self.name or not isinstance(self.name, str):
            raise ValueError("name must be a…
11 0 Open
AI & LLM integration patterns easy

How to Build a System-User-Assistant Message List in Python

Use dataclasses to model a chat conversation and build the system/user/assistant message list expected by LLM APIs.

llm dataclass openai
Python
from dataclasses import dataclass, field
from typing import List


@dataclass
class Message:
    role: str
    content: str


@dataclass
class Conversation:
    messages: List[Message] = field(default_factory=list)

    def add_system(self, content: str) -> None:
        self.messages.append(Message(role="system", con…
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
Automation & scripting easy

How to Generate a cloud-init User Data Mock in Python

Generate a cloud-init user data mock for a VM using a dataclass and JSON in Python.

cloud-init automation dataclasses
Python
import json
from dataclasses import dataclass, asdict

@dataclass
class VMConfig:
    hostname: str
    cpus: int
    memory_mb: int
    ssh_key: str

def generate_cloud_init_mock(config: VMConfig) -> str:
    """Build a cloud-init user-data mock for a VM."""
    user_data = {
        "hostname": config.hostname,
    …
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.