attrs

26.1.0 · active · verified Sat Mar 28

attrs is a Python package that auto-generates dunder methods (__init__, __repr__, __eq__, etc.) for your classes via a declarative decorator, eliminating boilerplate. The modern API (`attrs.define`, `attrs.field`, `attrs.frozen`) was stabilised in v20.1.0 and the `attrs` import namespace was added in v21.3.0. The current version is 26.1.0 (released 2026). Releases are frequent and roughly follow a quarterly cadence; Python >=3.9 is required.

Warnings

Install

Imports

Quickstart

Define a slotted, validated attrs class with a mutable-default field, a frozen variant, and serialisation.

from attrs import define, field, frozen, Factory, asdict, evolve, validators

# Modern API — slots=True by default, converters run on setattr
@define
class Point:
    x: float
    y: float
    tags: list[str] = field(factory=list)  # safe mutable default

    @x.validator
    def _positive_x(self, attribute, value):
        if value < 0:
            raise ValueError(f"x must be non-negative, got {value}")

p = Point(1.0, 2.0)
p.tags.append("origin-area")
print(p)           # Point(x=1.0, y=2.0, tags=['origin-area'])
print(asdict(p))   # {'x': 1.0, 'y': 2.0, 'tags': ['origin-area']}

# Frozen (immutable) class — use evolve() to get a modified copy
@frozen
class Config:
    host: str = "localhost"
    port: int = 8080

cfg = Config()
new_cfg = evolve(cfg, port=9090)
print(new_cfg)     # Config(host='localhost', port=9090)

# Nested serialisation
@define
class Server:
    config: Config
    name: str

srv = Server(config=cfg, name="primary")
print(asdict(srv))

view raw JSON →