Convert Figma logo to code with AI

python-attrs logoattrs

Python Classes Without Boilerplate

5,527
388
5,527
142

Top Related Projects

A generic system for filtering Django QuerySets based on user selections

Dependency injection framework for Python

Quick Overview

The attrs library is a Python package that provides a simple and efficient way to create classes with attributes. It aims to reduce the boilerplate code required for defining classes and their attributes, making the code more concise and readable.

Pros

  • Reduced Boilerplate: attrs significantly reduces the amount of boilerplate code required for defining classes and their attributes, making the code more concise and maintainable.
  • Automatic Attribute Generation: attrs can automatically generate common methods, such as __init__, __repr__, and __eq__, based on the defined attributes.
  • Type Annotations: attrs integrates well with Python's type annotation system, allowing for better type checking and documentation.
  • Extensibility: attrs provides a flexible and extensible system for adding custom behavior to classes, such as validation, conversion, and serialization.

Cons

  • Learning Curve: While attrs simplifies class definition, it introduces a new set of concepts and syntax that developers need to learn, which may be a barrier for some.
  • Dependency: Using attrs introduces an additional dependency in the project, which may be a concern for some developers.
  • Limited Compatibility: attrs requires Python 2.7 or later, which may be a limitation for projects that need to support older versions of Python.
  • Potential Performance Impact: The automatic generation of methods by attrs may have a slight performance impact compared to manually written code, although this is generally negligible.

Code Examples

Here are a few examples of how to use the attrs library:

  1. Basic Class Definition:
import attr

@attr.s
class Person:
    name = attr.ib(type=str)
    age = attr.ib(type=int)
  1. Automatic Method Generation:
person = Person(name="Alice", age=30)
print(person)  # Output: Person(name='Alice', age=30)
  1. Validation and Conversion:
@attr.s
class Rectangle:
    width = attr.ib(type=float, validator=attr.validators.instance_of(float))
    height = attr.ib(type=float, converter=float)

rect = Rectangle(width="10.5", height="20.0")
print(rect.width, rect.height)  # Output: 10.5 20.0
  1. Extending Functionality:
import attr

@attr.s
class BankAccount:
    balance = attr.ib(type=float, default=0.0)

    @balance.validator
    def _check_balance(self, attribute, value):
        if value < 0:
            raise ValueError("Balance cannot be negative")

account = BankAccount(balance=-100.0)  # Raises ValueError

Getting Started

To get started with the attrs library, you can install it using pip:

pip install attrs

Once installed, you can start using attrs to define your classes. Here's a simple example:

import attr

@attr.s
class Person:
    name = attr.ib(type=str)
    age = attr.ib(type=int)

person = Person(name="Alice", age=30)
print(person)  # Output: Person(name='Alice', age=30)

In this example, we define a Person class using the @attr.s decorator. The class has two attributes, name and age, which are defined using the attr.ib() function. The type parameter specifies the expected type of the attribute.

You can further customize the behavior of your classes by using attr.ib() options, such as validator, converter, and default. The attrs documentation provides detailed information on these and other features.

Competitor Comparisons

A generic system for filtering Django QuerySets based on user selections

Pros of django-filter

  • Provides a powerful and flexible way to filter Django QuerySets, making it easier to build complex search and filtering functionality in web applications.
  • Supports a wide range of field types, including related fields, and provides a simple API for defining custom filters.
  • Integrates well with Django's admin interface, allowing for easy configuration and customization of filters.

Cons of django-filter

  • Requires more boilerplate code to set up and configure compared to attrs, as it is a more feature-rich and complex library.
  • May have a steeper learning curve for developers who are new to Django or filtering in web applications.

Code Comparison

attrs:

@attr.s
class Point:
    x = attr.ib()
    y = attr.ib()

django-filter:

class PersonFilter(filters.FilterSet):
    name = filters.CharFilter(lookup_expr='icontains')
    age = filters.NumberFilter(lookup_expr='gt')

    class Meta:
        model = Person
        fields = ['name', 'age']

Dependency injection framework for Python

Pros of python-dependency-injector

  • Flexibility: python-dependency-injector provides a flexible and extensible dependency injection framework, allowing for complex configurations and customization.
  • Testability: The framework promotes testability by making it easier to isolate and test individual components.
  • Modularity: python-dependency-injector encourages a modular design, making it easier to manage and maintain large-scale applications.

Cons of python-dependency-injector

  • Complexity: The framework can be more complex to set up and configure compared to simpler solutions like python-attrs.
  • Learning Curve: Developers may need to invest more time in understanding the concepts and features of python-dependency-injector.
  • Overhead: The additional layer of abstraction introduced by the dependency injection framework may add some overhead to the application.

Code Comparison

python-attrs:

@attrs.define
class Person:
    name: str
    age: int

person = Person(name="John", age=30)
print(person.name)  # Output: "John"

python-dependency-injector:

from dependency_injector import containers, providers

class PersonService:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I'm {self.age} years old.")

class Container(containers.DeclarativeContainer):
    person_service = providers.Singleton(PersonService, name="John", age=30)

container = Container()
person_service = container.person_service()
person_service.greet()  # Output: "Hello, my name is John and I'm 30 years old."

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

attrs

Documentation Downloads per month DOI

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.