Mengapa anda perlu menggunakan attrs lebih banyak

WBOY
Lepaskan: 2024-08-21 06:14:33
asal
760 orang telah melayarinya

Why should you use attrs more

pengenalan

Pustaka attrs Python ialah pengubah permainan untuk pembangun yang ingin memudahkan penciptaan kelas dan mengurangkan kod boilerplate. Perpustakaan ini juga dipercayai oleh NASA.
Dicipta oleh Hynek Schlawack pada 2015, attrs telah menjadi alat kegemaran dalam kalangan pembangun Python dengan pantas kerana keupayaannya menjana kaedah khas secara automatik dan menyediakan cara yang bersih dan deklaratif untuk mentakrifkan kelas.
kelas data ialah sejenis subset attr.

Mengapa attrs berguna:

  • Mengurangkan kod boilerplate
  • Meningkatkan kebolehbacaan dan kebolehselenggaraan kod
  • Menyediakan ciri berkuasa untuk pengesahan dan penukaran data
  • Meningkatkan prestasi melalui pelaksanaan yang dioptimumkan

2. Bermula dengan attrs

Pemasangan:
Untuk bermula dengan attrs, anda boleh memasangnya menggunakan pip:

pip install attrs
Salin selepas log masuk

Penggunaan asas:
Berikut ialah contoh mudah cara menggunakan attrs untuk mentakrifkan kelas:

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)
Salin selepas log masuk

3. Ciri Teras attrs

a. Penjanaan kaedah automatik:

attrs secara automatik menjana kaedah init, repr dan eq untuk kelas anda:

@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
Salin selepas log masuk

b. Definisi atribut dengan jenis dan nilai lalai:

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)
Salin selepas log masuk

c. Pengesah dan penukar:

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
Salin selepas log masuk

4. Penggunaan Lanjutan

a. Menyesuaikan tingkah laku atribut:

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')
Salin selepas log masuk

b. Contoh dan slot beku:

@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
Salin selepas log masuk

c. Fungsi kilang dan pemprosesan pasca-init:

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)
Salin selepas log masuk

5. Amalan Terbaik dan Perangkap Biasa

Amalan Terbaik:

  • Gunakan anotasi jenis untuk kebolehbacaan kod yang lebih baik dan sokongan IDE
  • Manfaatkan pengesah untuk integriti data
  • Gunakan kelas beku untuk objek tidak berubah
  • Manfaatkan penjanaan kaedah automatik untuk mengurangkan pertindihan kod

Perangkap biasa:

  • Terlupa menggunakan penghias @attr.s pada kelas
  • Terlalu banyak menggunakan pengesah kompleks yang boleh menjadi kaedah berasingan
  • Tidak mengambil kira kesan prestasi penggunaan meluas fungsi kilang

6. attrs vs Perpustakaan Lain

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)
Salin selepas log masuk

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/ ↩

Atas ialah kandungan terperinci Mengapa anda perlu menggunakan attrs lebih banyak. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!