Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
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…
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…
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.