Python Attrs Module
attrs is the Python package that will bring back the joy of writing classes by relieving you from the drudgery of implementing the object protocol (methods like __init__, __repr__, __eq__, etc.).
Note: Python 3.7+ introduced dataclasses, which are similar but less powerful than attrs.
Installation
pip install attrs
Basic Usage
Use the @define decorator (modern alias for @attr.s) to declare a class.
from attrs import define
@define
class Point:
x: int
y: int
p = Point(1, 2)
print(p)
# Output: Point(x=1, y=2)
print(p == Point(1, 2))
# Output: True
Validation
You can add validators to fields.
from attrs import define, field, validators
@define
class User:
email: str = field(validator=validators.instance_of(str))
age: int = field(validator=validators.ge(18))
# User(email="test", age=10) # Raises ValueError
Converters
Converters run automatically when setting a value.
from attrs import define, field
@define
class Coordinates:
x: int = field(converter=int)
y: int = field(converter=int)
c = Coordinates("1", 2.5)
print(c)
# Output: Coordinates(x=1, y=2)
Immutability (Frozen Classes)
You can easily make instances immutable.
from attrs import define
@define(frozen=True)
class Config:
host: str
port: int
c = Config("localhost", 8080)
# c.port = 9000 # Raises attr.exceptions.FrozenInstanceError