attrs
Class-building library that generates boilerplate for attributes, validation, equality and immutability.
Official Documentation ↗attrs 23.2+ / Python 3.8+. Check the official docs for the latest API surface.Installation
pip install attrsMethods
No methods match this filter.
Overview
attrs removes class boilerplate by generating init, repr, equality and comparison methods from declared attributes, with optional validation, conversion and immutability.
Core Methods
Decorate a class with define, declare fields with field, and attach validators or converters. frozen makes instances immutable and hashable, and slots are enabled by default.
Usage Notes
Use attrs for value objects and configuration with clear validation. Prefer frozen for data that should not change, and converters to normalize input at construction.
Common Pitfalls
Because slots are default, dynamically adding attributes fails unless slots=False is set. frozen instances cannot be mutated, so mutation-based code must be refactored. Validators do not run on every raw attribute access, only through supported assignment paths.
FAQ
- How is attrs different from dataclasses?
- attrs inspired dataclasses and adds more features out of the box: validators, converters, slots by default, frozen instances and a richer field API, while remaining compatible.
- What does frozen do?
- frozen makes instances immutable after creation and generates a hash, so they can be used as dictionary keys or set members as long as all fields are hashable.
- How do I add validation?
- Attach a validator to a field, or use an on_setattr hook, so assignments are checked. Validation runs on initialization and, depending on settings, on later assignments.
Report a problem with this API docOpens a pre-filled issue on GitHub.