Hướng dẫn python-attrs
Basics#The simplest possible usage is: Show >>> from attrs import define, field >>> @define ... class Empty: ... pass >>> Empty() Empty() >>> Empty() == Empty() True >>> Empty() is Empty() False So in other words: But you’ll usually want some data on your classes, so let’s add some: >>> @define ... class Coordinates: ... x: int ... y: int By default, all features are added, so you immediately have a
fully functional data class with a nice >>> c1 = Coordinates(1, 2) >>> c1 Coordinates(x=1, y=2) >>> c2 = Coordinates(x=2, y=1) >>> c2 Coordinates(x=2, y=1) >>> c1 == c2 False As shown, the generated For private attributes, >>> @define ... class C: ... _x: int >>> C(x=1) C(_x=1) If you want to initialize your private attributes yourself, you can do that too: >>> @define ... class C: ... _x: int = field(init=False, default=42) >>> C() C(_x=42) >>> C(23) Traceback (most recent call last): ... TypeError: __init__() takes exactly 1 argument (2 given) An additional way of defining attributes is supported too. This is useful in
times when you want to enhance classes that are not yours (nice >>> class SomethingFromSomeoneElse: ... def __init__(self, x): ... self.x = x >>> SomethingFromSomeoneElse = define( ... these={ ... "x": field() ... }, init=False)(SomethingFromSomeoneElse) >>> SomethingFromSomeoneElse(1) SomethingFromSomeoneElse(x=1) Subclassing is bad for you, but >>> @define(slots=False) ... class A: ... a: int ... def get_a(self): ... return self.a >>> @define(slots=False) ... class B: ... b: int >>> @define(slots=False) ... class C(B, A): ... c: int >>> i = C(1, 2, 3) >>> i C(a=1, b=2, c=3) >>> i == C(1, 2, 3) True >>> i.get_a() 1 Slotted classes, which are the default for the new APIs, don’t play well with multiple inheritance so we don’t use them in the example. The order of the attributes is defined by the MRO. Keyword-only Attributes#You can also add keyword-only attributes: >>> @define ... class A: ... a: int = field(kw_only=True) >>> A() Traceback (most recent call last): ... TypeError: A() missing 1 required keyword-only argument: 'a' >>> A(a=1) A(a=1)
>>> @define(kw_only=True) ... class A: ... a: int ... b: int >>> A(1, 2) Traceback (most recent call last): ... TypeError: __init__() takes 1 positional argument but 3 were given >>> A(a=1, b=2) A(a=1, b=2) If you create an attribute with Keyword-only attributes allow subclasses to add attributes without default values, even if the base class defines attributes with default values: >>> @define ... class A: ... a: int = 0 >>> @define ... class B(A): ... b: int = field(kw_only=True) >>> B(b=1) B(a=0, b=1) >>> B() Traceback (most recent call last): ... TypeError: B() missing 1 required keyword-only argument: 'b' If
you don’t set >>> @define ... class A: ... a: int = 0 >>> @define ... class B(A): ... b: int Traceback (most recent call last): ... ValueError: No mandatory attributes allowed after an attribute with a default value or factory. Attribute in question: Attribute(name='b', default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, converter=None, metadata=mappingproxy({}), type=int, kw_only=False) Converting to Collections Types#When you have a class with data, it often is very convenient to transform that class into a
>>> from attrs import asdict >>> asdict(Coordinates(x=1, y=2)) {'x': 1, 'y': 2} Some fields cannot or should not be transformed. For that, >>> @define ... class User: ... email: str ... password: str >>> @define ... class UserList: ... users: list[User] >>> asdict(UserList([User("", "s33kred"), ... User("", "p4ssw0rd")]), ... filter=lambda attr, value: attr.name != "password") {'users': [{'email': ''}, {'email': ''}]} For the common case where you want to
>>> from attrs import asdict, filters, fields >>> @define ... class User: ... login: str ... password: str ... id: int >>> asdict( ... User("jane", "s33kred", 42), ... filter=filters.exclude(fields(User).password, int)) {'login': 'jane'} >>> @define ... class C: ... x: str ... y: str ... z: int >>> asdict(C("foo", "2", 3), ... filter=filters.include(int, fields(C).x)) {'x': 'foo', 'z': 3} Other times, all you want is a tuple and >>> import sqlite3 >>> from attrs import astuple >>> @define ... class Foo: ... a: int ... b: int >>> foo = Foo(2, 3) >>> with sqlite3.connect(":memory:") as conn: ... c = conn.cursor() ... c.execute("CREATE TABLE foo (x INTEGER PRIMARY KEY ASC, y)") ... c.execute("INSERT INTO foo VALUES (?, ?)", astuple(foo)) ... foo2 = Foo(*c.execute("SELECT x, y FROM foo").fetchone()) For more advanced transformations and conversions, we recommend you look at a companion library (such as cattrs). Defaults#Sometimes you want to have default values for your initializer. And sometimes you even want mutable objects as default values (ever accidentally used >>> import collections >>> @define ... class Connection: ... socket: int ... @classmethod ... def connect(cls, db_string): ... # ... connect somehow to db_string ... ... return cls(socket=42) >>> @define ... class ConnectionPool: ... db_string: str ... pool: collections.deque = Factory(collections.deque) ... debug: bool = False ... def get_connection(self): ... try: ... return self.pool.pop() ... except IndexError: ... if self.debug: ... print("New connection!") ... return Connection.connect(self.db_string) ... def free_connection(self, conn): ... if self.debug: ... print("Connection returned!") ... self.pool.appendleft(conn) ... >>> cp = ConnectionPool("postgres://localhost") >>> cp ConnectionPool(db_string='postgres://localhost', pool=deque([]), debug=False) >>> conn = cp.get_connection() >>> conn Connection(socket=42) >>> cp.free_connection(conn) >>> cp ConnectionPool(db_string='postgres://localhost', pool=deque([Connection(socket=42)]), debug=False) More information on why class methods for constructing objects are awesome can be found in this insightful blog post. Default factories can also be set using the >>> @define ... class C: ... x: int = 1 ... y: int = field() ... @y.default ... def _any_name_except_a_name_of_an_attribute(self): ... return self.x + 1 ... z: list = field(factory=list) >>> C() C(x=1, y=2, z=[]) Please keep in mind that the decorator approach only works if the attribute in question has a Validators#Although your initializers should do as little as possible (ideally: just initialize your instance according to the arguments!), it can come in handy to do some kind of validation on the arguments.
You can use a decorator: >>> @define ... class C: ... x: int = field() ... @x.validator ... def check(self, attribute, value): ... if value > 42: ... raise ValueError("x must be smaller or equal to 42") >>> C(42) C(x=42) >>> C(43) Traceback (most recent call last): ... ValueError: x must be smaller or equal to 42 …or a callable… >>> from attrs import validators >>> def x_smaller_than_y(instance, attribute, value): ... if value >= instance.y: ... raise ValueError("'x' has to be smaller than 'y'!") >>> @define ... class C: ... x: int = field(validator=[validators.instance_of(int), ... x_smaller_than_y]) ... y: int >>> C(x=3, y=4) C(x=3, y=4) >>> C(x=4, y=3) Traceback (most recent call last): ... ValueError: 'x' has to be smaller than 'y'! …or both at once: >>> @define ... class C: ... x: int = field(validator=validators.instance_of(int)) ... @x.validator ... def fits_byte(self, attribute, value): ... if not 0 <= value < 256: ... raise ValueError("value out of bounds") >>> C(128) C(x=128) >>> C("128") Traceback (most recent call last): ... TypeError: ("'x' must be Please note
that the decorator approach only works if – and only if! – the attribute in question has a
>>> @define ... class C: ... x: int = field(validator=validators.instance_of(int)) >>> C(42) C(x=42) >>> C("42") Traceback (most recent call last): ... TypeError: ("'x' must be Please note that if you use
Check out Validators for more details. Conversion#Attributes can have a >>> @define ... class C: ... x: int = field(converter=int) >>> o = C("1") >>> o.x 1 Please note that converters only run on initialization. Check out Converters for more details. Metadata#All >>> from attrs import fields >>> @define ... class C: ... x = field(metadata={'my_metadata': 1}) >>> fields(C).x.metadata mappingproxy({'my_metadata': 1}) >>> fields(C).x.metadata['my_metadata'] 1 Metadata is not used by If you’re the author of a third-party library with Types#
>>> from attrs import fields >>> @define ... class C: ... x: int >>> fields(C).x.type If you don’t mind annotating all attributes, you can even drop the >>> import typing >>> from attrs import fields >>> @define ... class AutoC: ... cls_var: typing.ClassVar[int] = 5 # this one is ignored ... l: list[int] = Factory(list) ... x: int = 1 ... foo: str = "every attrib needs a type if auto_attribs=True" ... bar: typing.Any = None >>> fields(AutoC).l.type list[int] >>> fields(AutoC).x.type The generated If your annotations contain strings (e.g. forward references), you can resolve these after all references have been defined by using
>>> from attrs import fields, resolve_types >>> @define ... class A: ... a: 'list[A]' ... b: 'B' ... >>> @define ... class B: ... a: A ... >>> fields(A).a.type 'list[A]' >>> fields(A).b.type 'B' >>> resolve_types(A, globals(), locals()) Note If you find yourself using string type annotations to handle forward references, wrap the entire type annotation in quotes instead of only the type you need a forward reference to (so Warning
Slots#Slotted
classes have several advantages on CPython. Defining >>> import attr >>> @attr.s(slots=True) ... class Coordinates: ... x: int ... y: int Immutability#Sometimes you have instances that shouldn’t be changed after instantiation. Immutability is especially popular in functional programming and is generally a very good thing. If you’d like to enforce it, >>> @frozen ... class C: ... x: int >>> i = C(1) >>> i.x = 2 Traceback (most recent call last): ... attr.exceptions.FrozenInstanceError: can't set attribute >>> i.x 1 Please note that true immutability is impossible in Python but it will get you 99% there. By themselves, immutable classes are useful for long-lived objects that should never change; like configurations for example. In order to use them in regular program flow, you’ll need a way to easily create new instances with changed attributes. In Clojure that function is called assoc and
>>> from attrs import evolve, frozen >>> @frozen ... class C: ... x: int ... y: int >>> i1 = C(1, 2) >>> i1 C(x=1, y=2) >>> i2 = evolve(i1, y=3) >>> i2 C(x=1, y=3) >>> i1 == i2 False Other Goodies#Sometimes you may want to create a class programmatically. >>> from attrs import fields, make_class >>> @define ... class C1: ... x = field() ... y = field() >>> C2 = make_class("C2", ["x", "y"]) >>> fields(C1) == fields(C2) True You can still have power over the attributes if you pass a dictionary of name: >>> from attrs import make_class >>> C = make_class("C", {"x": field(default=42), ... "y": field(default=Factory(list))}, ... repr=False) >>> i = C() >>> i # no repr added! <__main__.C object at ...> >>> i.x 42 >>> i.y [] If you need to dynamically make a class with >>> from attrs import make_class >>> class D: ... def __eq__(self, other): ... return True # arbitrary example >>> C = make_class("C", {}, bases=(D,), cmp=False) >>> isinstance(C(), D) True Sometimes, you want to have your class’s >>> @define ... class C: ... x: int ... y: int ... z: int = field(init=False) ... ... def __attrs_post_init__(self): ... self.z = self.x + self.y >>> obj = C(x=1, y=2) >>> obj C(x=1, y=2, z=3) You can exclude single attributes from certain methods: >>> @define ... class C: ... user: str ... password: str = field(repr=False) >>> C("me", "s3kr3t") C(user='me') Alternatively,
to influence how the generated >>> @define ... class C: ... user: str ... password: str = field(repr=lambda value: '***') >>> C("me", "s3kr3t") C(user='me', password=***) |