Skip to main content

Classes Without Boilerplate

Project description

attrs

attrs is the Python package that will bring back the joy of writing classes by relieving you from the drudgery of implementing object protocols (aka dunder methods). Trusted by NASA for Mars missions since 2020!

Its main goal is to help you to write concise and correct software without slowing down your code.

Sponsors

attrs would not be possible without our amazing sponsors. Especially those generously supporting us at the The Organization tier and higher:

Please consider joining them to help make attrs’s maintenance more sustainable!

Example

attrs gives you a class decorator and a way to declaratively define the attributes on that class:

>>> from attrs import asdict, define, make_class, Factory

>>> @define
... class SomeClass:
...     a_number: int = 42
...     list_of_numbers: list[int] = Factory(list)
...
...     def hard_math(self, another_number):
...         return self.a_number + sum(self.list_of_numbers) * another_number


>>> sc = SomeClass(1, [1, 2, 3])
>>> sc
SomeClass(a_number=1, list_of_numbers=[1, 2, 3])

>>> sc.hard_math(3)
19
>>> sc == SomeClass(1, [1, 2, 3])
True
>>> sc != SomeClass(2, [3, 2, 1])
True

>>> asdict(sc)
{'a_number': 1, 'list_of_numbers': [1, 2, 3]}

>>> SomeClass()
SomeClass(a_number=42, list_of_numbers=[])

>>> C = make_class("C", ["a", "b"])
>>> C("foo", "bar")
C(a='foo', b='bar')

After declaring your attributes, attrs gives you:

  • a concise and explicit overview of the class's attributes,
  • a nice human-readable __repr__,
  • equality-checking methods,
  • an initializer,
  • and much more,

without writing dull boilerplate code again and again and without runtime performance penalties.


This example uses attrs's modern APIs that have been introduced in version 20.1.0, and the attrs package import name that has been added in version 21.3.0. The classic APIs (@attr.s, attr.ib, plus their serious-business aliases) and the attr package import name will remain indefinitely.

Check out On The Core API Names for an in-depth explanation!

Hate Type Annotations!?

No problem! Types are entirely optional with attrs. Simply assign attrs.field() to the attributes instead of annotating them with types:

from attrs import define, field

@define
class SomeClass:
    a_number = field(default=42)
    list_of_numbers = field(factory=list)

Data Classes

On the tin, attrs might remind you of dataclasses (and indeed, dataclasses are a descendant of attrs). In practice it does a lot more and is more flexible. For instance, it allows you to define special handling of NumPy arrays for equality checks, allows more ways to plug into the initialization process, has a replacement for __init_subclass__, and allows for stepping through the generated methods using a debugger.

For more details, please refer to our comparison page, but generally speaking, we are more likely to commit crimes against nature to make things work that one would expect to work, but that are quite complicated in practice.

Project Information

attrs for Enterprise

Available as part of the Tidelift Subscription.

The maintainers of attrs and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. Learn more.

Release Information

Backwards-incompatible Changes

  • attrs.evolve() doesn't accept the inst argument as a keyword argument anymore. Pass it as the first positional argument instead. #1264

  • attrs.validators.provides() has been removed. The removed code is available as a gist for convenient copy and pasting. #1265

  • All packaging metadata except from __version__ and __version_info__ has been removed from the attr and attrs modules (for example, attrs.__url__).

    Please use importlib.metadata or importlib_metadata instead. #1268

  • Speed up the generated __eq__ methods significantly by generating a chain of attribute comparisons instead of constructing and comparing tuples. This change arguably makes the behavior more correct, but changes it if an attribute compares equal by identity but not value, like float('nan'). #1310

Deprecations

  • The repr_ns argument to attr.s is now deprecated. It was a workaround for nested classes in Python 2 and is pointless in Python 3. #1263
  • The hash argument to @attr.s, @attrs.define, and make_class() is now deprecated in favor of unsafe_hash, as defined by PEP 681. #1323

Changes

  • Allow original slotted functools.cached_property classes to be cleaned by garbage collection. Allow super() calls in slotted cached properties. #1221

  • Our type stubs now use modern type notation and are organized such that VS Code's quick-fix prefers the attrs namespace. #1234

  • Preserve AttributeError raised by properties of slotted classes with functools.cached_properties. #1253

  • It is now possible to wrap a converter into an attrs.Converter and get the current instance and/or the current field definition passed into the converter callable.

    Note that this is not supported by any type checker, yet. #1267

  • attrs.make_class() now populates the __annotations__ dict of the generated class, so that attrs.resolve_types() can resolve them. #1285

  • Added the attrs.validators.or_() validator. #1303

  • The combination of a __attrs_pre_init__ that takes arguments, a kw-only field, and a default on that field does not crash anymore. #1319

  • attrs.validators.in_() now transforms certain unhashable options to tuples to keep the field hashable.

    This allows fields that use this validator to be used with, for example, attrs.filters.include(). #1320

  • If a class has an inherited method called __attrs_init_subclass__, it is now called once the class is done assembling.

    This is a replacement for Python's __init_subclass__ and useful for registering classes, and similar. #1321


Full changelog →

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

attrs-24.1.0.tar.gz (792.6 kB view hashes)

Uploaded Source

Built Distribution

attrs-24.1.0-py3-none-any.whl (63.9 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page