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.
import 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
Related Packages
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.