Reference library

Python Code Samples

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

83 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
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
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 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 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 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 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 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

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.