attrs
UtilitiesClass boilerplate-free
What is attrs?
attrs (imported as attr) is a Python package that lets you write concise, correct Python classes without boilerplate. It automatically generates __init__, __repr__, __eq__, and other dunder methods, and additionally supports validators, converters, slots, and frozen (immutable) classes.
attrs is a popular choice for defining clean data-holding classes in Python, and it directly inspired Python's built-in dataclasses module. In PyRun, attrs loads instantly via micropip, making it a great library to explore when learning about class design patterns.
Code Example
Clean Python classes with attrs validators.
Attrs Data Classes
Try in Editorimport attr
@attr.s(auto_attribs=True)
class Point:
x: float
y: float
def distance_to(self, other: "Point") -> float:
return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5
@attr.s(auto_attribs=True)
class Polygon:
name: str
vertices: list = attr.Factory(list)
def perimeter(self) -> float:
pts = self.vertices + [self.vertices[0]]
return sum(pts[i].distance_to(pts[i+1]) for i in range(len(pts)-1))
triangle = Polygon("Triangle", [
Point(0, 0), Point(4, 0), Point(0, 3)
])
print(repr(triangle))
print(f"Perimeter: {triangle.perimeter():.4f}")
print(f"Expected : 12.0000 (3-4-5 right triangle)")Why run attrs in PyRun?
- ✦ Zero setup — no pip install, no virtual environment, no Python download
- ✦ Instant results — powered by WebAssembly, runs locally in your browser
- ✦ Share your code — generate a link and anyone can run it instantly
- ✦ Works offline — after first load, PyRun runs without internet