Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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.
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}={…
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.
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…
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.
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…
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).
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…
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.
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…
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.
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
…
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.
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
…
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.
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…
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.
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…
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.
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…
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.
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}…
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.
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…
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.
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…
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.
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…
How to Define Dataclass Field Defaults in Python
Implement a Python dataclass with default values for simple fields and default factories for mutable collections.
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)
…
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.
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)
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.
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…
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.
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:
…
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.
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 …
Parse CSV Data with a Python Class
Encapsulate CSV file loading and column/row access methods in a reusable DataParser class for beginners.
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.…
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.
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…
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.
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…
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.
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)
…
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.
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,
…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.