首頁 >後端開發 >Python教學 >為什麼你應該更多地使用 attrs

為什麼你應該更多地使用 attrs

WBOY
WBOY原創
2024-08-21 06:14:33860瀏覽

Why should you use attrs more

介紹

Python 的 attrs 庫對於希望簡化類別創建並減少樣板程式碼的開發人員來說是一個遊戲規則改變者。這個函式庫甚至受到 NASA 的信任。
attrs 由 Hynek Schlawack 於 2015 年創建,因其能夠自動生成特殊方法並提供乾淨的聲明式方式來定義類,而迅速成為 Python 開發人員最喜歡的工具。
資料類別是屬性的子集。

為什麼 attrs 有用:

  • 減少樣板代碼
  • 提高程式碼可讀性和可維護性
  • 提供強大的資料驗證與轉換功能
  • 透過最佳化實施提高效能

2. 屬性入門

安裝:
要開始使用 attrs,您可以使用 pip 安裝它:

pip install attrs

基本用法:
這是一個如何使用 attrs 定義類別的簡單範例:

import attr

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

# Creating an instance
person = Person("Alice", 30)
print(person)  # Person(name='Alice', age=30)

3. attrs的核心特性

一個。自動方法產生:

attrs 會自動為您的類別產生 initrepreq 方法:

@attr.s
class Book:
    title = attr.ib()
    author = attr.ib()
    year = attr.ib()

book1 = Book("1984", "George Orwell", 1949)
book2 = Book("1984", "George Orwell", 1949)

print(book1)  # Book(title='1984', author='George Orwell', year=1949)
print(book1 == book2)  # True

b.具有類型和預設值的屬性定義:

import attr
from typing import List

@attr.s
class Library:
    name = attr.ib(type=str)
    books = attr.ib(type=List[str], default=attr.Factory(list))
    capacity = attr.ib(type=int, default=1000)

library = Library("City Library")
print(library)  # Library(name='City Library', books=[], capacity=1000)

c.驗證器和轉換器:

import attr

def must_be_positive(instance, attribute, value):
    if value <= 0:
        raise ValueError("Value must be positive")

@attr.s
class Product:
    name = attr.ib()
    price = attr.ib(converter=float, validator=[attr.validators.instance_of(float), must_be_positive])

product = Product("Book", "29.99")
print(product)  # Product(name='Book', price=29.99)

try:
    Product("Invalid", -10)
except ValueError as e:
    print(e)  # Value must be positive

4. 高級使用

一個。自訂屬性行為:

import attr

@attr.s
class User:
    username = attr.ib()
    _password = attr.ib(repr=False)  # Exclude from repr

    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, value):
        self._password = hash(value)  # Simple hashing for demonstration

user = User("alice", "secret123")
print(user)  # User(username='alice')

b.凍結的實例和槽:

@attr.s(frozen=True) # slots=True is the default
class Point:
    x = attr.ib()
    y = attr.ib()

point = Point(1, 2)
try:
    point.x = 3  # This will raise an AttributeError
except AttributeError as e:
    print(e)  # can't set attribute

c.工廠函數與初始化後處理:

import attr
import uuid

@attr.s
class Order:
    id = attr.ib(factory=uuid.uuid4)
    items = attr.ib(factory=list)
    total = attr.ib(init=False)

    def __attrs_post_init__(self):
        self.total = sum(item.price for item in self.items)

@attr.s
class Item:
    name = attr.ib()
    price = attr.ib(type=float)

order = Order(items=[Item("Book", 10.99), Item("Pen", 1.99)])
print(order)  # Order(id=UUID('...'), items=[Item(name='Book', price=10.99), Item(name='Pen', price=1.99)], total=12.98)

5. 最佳實務與常見陷阱

最佳實踐:

  • 使用類型註解以獲得更好的程式碼可讀性和 IDE 支援
  • 利用驗證器確保資料完整性
  • 對不可變物件使用凍結類別
  • 利用自動方法產生來減少程式碼重複

常見陷阱:

  • 忘記在類別上使用 @attr.s 裝飾器
  • 過度使用可能是單獨方法的複雜驗證器
  • 不考慮大量使用工廠函數對性能的影響

6. attrs 與其他函式庫的比較

Library Features Performance Community
attrs Automatic method generation, attribute definition with types and default values, validators and converters Better performance than manual code Active community
pydantic Data validation and settings management, automatic method generation, attribute definition with types and default values, validators and converters Good performance Active community
dataclasses Built into Python 3.7+, making them more accessible Tied to the Python version Built-in Python library

attrs and dataclasses are faster than pydantic1.

Comparison with dataclasses:

  • attrs is more feature-rich and flexible
  • dataclasses are built into Python 3.7+, making them more accessible
  • attrs has better performance in most cases
  • dataclasses are tied to the Python version, while attrs as an external library can be used with any Python version.

Comparison with pydantic:

  • pydantic is focused on data validation and settings management
  • attrs is more general-purpose and integrates better with existing codebases
  • pydantic has built-in JSON serialization, while attrs requires additional libraries

When to choose attrs:

  • For complex class hierarchies with custom behaviors
  • When you need fine-grained control over attribute definitions
  • For projects that require Python 2 compatibility (though less relevant now)

7. Performance and Real-world Applications

Performance:
attrs generally offers better performance than manually written classes or other libraries due to its optimized implementations.

Real-world example:

from attr import define, Factory
from typing import List, Optional

@define
class Customer:
    id: int
    name: str
    email: str
    orders: List['Order'] = Factory(list)

@define
class Order:
    id: int
    customer_id: int
    total: float
    items: List['OrderItem'] = Factory(list)

@define
class OrderItem:
    id: int
    order_id: int
    product_id: int
    quantity: int
    price: float

@define
class Product:
    id: int
    name: str
    price: float
    description: Optional[str] = None

# Usage
customer = Customer(1, "Alice", "alice@example.com")
product = Product(1, "Book", 29.99, "A great book")
order_item = OrderItem(1, 1, 1, 2, product.price)
order = Order(1, customer.id, 59.98, [order_item])
customer.orders.append(order)

print(customer)

8. Conclusion and Call to Action

attrs is a powerful library that simplifies Python class definitions while providing robust features for data validation and manipulation. Its ability to reduce boilerplate code, improve readability, and enhance performance makes it an invaluable tool for Python developers.

Community resources:

  • GitHub repository: https://github.com/python-attrs/attrs
  • Documentation: https://www.attrs.org/
  • PyPI page: https://pypi.org/project/attrs/

Try attrs in your next project and experience its benefits firsthand. Share your experiences with the community and contribute to its ongoing development. Happy coding!


  1. https://stefan.sofa-rockers.org/2020/05/29/attrs-dataclasses-pydantic/ ↩

以上是為什麼你應該更多地使用 attrs的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn