gitmyhub

attrs

Python ★ 5.8k updated 2h ago

Python Classes Without Boilerplate

attrs is a Python library that auto-generates class boilerplate, __init__, __repr__, and comparison methods, from a simple @define decorator, so you stop writing repetitive code every time you define a class.

Pythonsetup: easycomplexity 2/5

attrs is a Python library that reduces the amount of repetitive code needed when writing classes. In standard Python, defining a class with several attributes means writing the same patterns over and over: an __init__ method to accept and assign each value, a __repr__ method so the object prints usefully, equality methods so two instances can be compared, and so on. attrs generates all of that automatically from a simple declaration.

You define a class with the @define decorator, then list your attributes as annotated fields. From that declaration, attrs creates a working initializer with default values, a readable string representation, and comparison operators, all without you writing any of that code manually. Type annotations are supported but not required. If you prefer not to annotate types, you can use attrs.field() assignments instead.

The library predates Python's built-in dataclasses module, which was directly influenced by attrs. The two cover similar ground, but attrs goes further in several areas: more control over initialization hooks, better support for custom equality logic (useful when working with libraries like NumPy), and a debugger-friendly approach to generated methods. The README points to a comparison page for a full breakdown of the differences.

attrs works well with validators, converters, and custom serialization. The asdict() function converts an attrs instance to a plain dictionary, which is useful for JSON output or logging. The library has a community of third-party extensions listed in the project wiki, covering things like serialization formats and integrations with other frameworks.

The project is well-established and has been used in production environments including NASA Mars missions. It is installable from PyPI with a standard pip install. Documentation is available at attrs.org, and support questions can be asked on Stack Overflow with the python-attrs tag. The library has been in active development since 2015.

Where it fits