Changelog¶
Versions follow CalVer with a strict backwards compatibility policy. The third digit is only for regressions.
20.3.0 (2020-11-05)¶
Backward-incompatible Changes¶
attr.define(),attr.frozen(),attr.mutable(), andattr.field()remain provisional.This release does not change change anything about them and they are already used widely in production though.
If you wish to use them together with mypy, you can simply drop this plugin into your project.
Feel free to provide feedback to them in the linked issue #668.
We will release the
attrsnamespace once we have the feeling that the APIs have properly settled. #668
Changes¶
attr.s()now has a field_transformer hook that is called for allAttributes and returns a (modified or updated) list ofAttributeinstances.attr.asdict()has a value_serializer hook that can change the way values are converted. Both hooks are meant to help with data (de-)serialization workflows. #653kw_only=Truenow works on Python 2. #700attr.asdict()andattr.astuple()now treatfrozensets likesets with regards to the retain_collection_types argument. #704The type stubs for
attr.s()andattr.make_class()are not missing the collect_by_mro argument anymore. #711
20.2.0 (2020-09-05)¶
Backward-incompatible Changes¶
attr.define(),attr.frozen(),attr.mutable(), andattr.field()remain provisional.This release fixes a bunch of bugs and ergonomics but they remain mostly unchanged.
If you wish to use them together with mypy, you can simply drop this plugin into your project.
Feel free to provide feedback to them in the linked issue #668.
We will release the
attrsnamespace once we have the feeling that the APIs have properly settled. #668
Changes¶
attr.define()et al now correct detect__eq__and__ne__. #671attr.define()et al’s hybrid behavior now also works correctly when arguments are passed. #675It’s possible to define custom
__setattr__methods on slotted classes again. #681In 20.1.0 we introduced the
inheritedattribute on theattr.Attributeclass to differentiate attributes that have been inherited and those that have been defined directly on the class.It has shown to be problematic to involve that attribute when comparing instances of
attr.Attributethough, because when sub-classing, attributes from base classes are suddenly not equal to themselves in a super class.Therefore the
inheritedattribute will now be ignored when hashing and comparing instances ofattr.Attribute. #684zope.interfaceis now a “soft dependency” when running the test suite; ifzope.interfaceis not installed when running the test suite, the interface-related tests will be automatically skipped. #685The ergonomics of creating frozen classes using
@define(frozen=True)and sub-classing frozen classes has been improved: you don’t have to seton_setattr=Noneanymore. #687
20.1.0 (2020-08-20)¶
Backward-incompatible Changes¶
Python 3.4 is not supported anymore. It has been unsupported by the Python core team for a while now, its PyPI downloads are negligible, and our CI provider removed it as a supported option.
It’s very unlikely that
attrswill break under 3.4 anytime soon, which is why we do not block its installation on Python 3.4. But we don’t test it anymore and will block it once someone reports breakage. #608
Deprecations¶
Less of a deprecation and more of a heads up: the next release of
attrswill introduce anattrsnamespace. That means that you’ll finally be able to runimport attrswith new functions that aren’t cute abbreviations and that will carry better defaults.This should not break any of your code, because project-local packages have priority before installed ones. If this is a problem for you for some reason, please report it to our bug tracker and we’ll figure something out.
The old
attrnamespace isn’t going anywhere and its defaults are not changing – this is a purely additive measure. Please check out the linked issue for more details.These new APIs have been added provisionally as part of #666 so you can try them out today and provide feedback. Learn more in the API docs. #408
Changes¶
Added
attr.resolve_types(). It ensures that all forward-references and types in string form are resolved into concrete types.You need this only if you need concrete types at runtime. That means that if you only use types for static type checking, you do not need this function. #288, #302
Added
@attr.s(collect_by_mro=False)argument that if set toTruefixes the collection of attributes from base classes.It’s only necessary for certain cases of multiple-inheritance but is kept off for now for backward-compatibility reasons. It will be turned on by default in the future.
As a side-effect,
attr.Attributenow always has aninheritedattribute indicating whether an attribute on a class was directly defined or inherited. #428, #635On Python 3, all generated methods now have a docstring explaining that they have been created by
attrs. #506It is now possible to prevent
attrsfrom auto-generating the__setstate__and__getstate__methods that are required for pickling of slotted classes.Either pass
@attr.s(getstate_setstate=False)or pass@attr.s(auto_detect=True)and implement them yourself: ifattrsfinds either of the two methods directly on the decorated class, it assumes implicitlygetstate_setstate=False(and implements neither).This option works with dict classes but should never be necessary. #512, #513, #642
Fixed a
ValueError: Cell is emptybug that could happen in some rare edge cases. #590attrscan now automatically detect your own implementations and inferinit=False,repr=False,eq=False,order=False, andhash=Falseif you set@attr.s(auto_detect=True).attrswill ignore inherited methods. If the argument implies more than one method (e.g.eq=Truecreates both__eq__and__ne__), it’s enough for one of them to exist andattrswill create neither.This feature requires Python 3. #607
Added
attr.converters.pipe(). The feature allows combining multiple conversion callbacks into one by piping the value through all of them, and retuning the last result.As part of this feature, we had to relax the type information for converter callables. #618
Fixed serialization behavior of non-slots classes with
cache_hash=True. The hash cache will be cleared on operations which make “deep copies” of instances of classes with hash caching, though the cache will not be cleared with shallow copies like those made bycopy.copy().Previously,
copy.deepcopy()or serialization and deserialization withpicklewould result in an un-initialized object.This change also allows the creation of
cache_hash=Trueclasses with a custom__setstate__, which was previously forbidden (#494). #620It is now possible to specify hooks that are called whenever an attribute is set after a class has been instantiated.
You can pass
on_setattrboth to@attr.s()to set the default for all attributes on a class, and to@attr.ib()to overwrite it for individual attributes.attrsalso comes with a new moduleattr.settersthat brings helpers that run validators, converters, or allow to freeze a subset of attributes. #645, #660Provisional APIs called
attr.define(),attr.mutable(), andattr.frozen()have been added.They are only available on Python 3.6 and later, and call
attr.s()with different default values.If nothing comes up, they will become the official way for creating classes in 20.2.0 (see above).
Please note that it may take some time until mypy – and other tools that have dedicated support for
attrs– recognize these new APIs. Please do not open issues on our bug tracker, there is nothing we can do about it. #666We have also provisionally added
attr.field()that supplantsattr.ib(). It also requires at least Python 3.6 and is keyword-only. Other than that, it only dropped a few arguments, but changed no defaults.As with
attr.s():attr.ib()is not going anywhere. #669
19.3.0 (2019-10-15)¶
19.2.0 (2019-10-01)¶
Backward-incompatible Changes¶
Removed deprecated
Attributeattributeconvertper scheduled removal on 2019/1. This planned deprecation is tracked in issue #307. #504__lt__,__le__,__gt__, and__ge__do not consider subclasses comparable anymore.This has been deprecated since 18.2.0 and was raising a
DeprecationWarningfor over a year. #570
Deprecations¶
The
cmpargument toattr.s()andattr.ib()is now deprecated.Please use
eqto add equality methods (__eq__and__ne__) andorderto add ordering methods (__lt__,__le__,__gt__, and__ge__) instead – just like with dataclasses.Both are effectively
Trueby default but it’s enough to seteq=Falseto disable both at once. Passingeq=False, order=Trueexplicitly will raise aValueErrorthough.Since this is arguably a deeper backward-compatibility break, it will have an extended deprecation period until 2021-06-01. After that day, the
cmpargument will be removed.attr.Attributealso isn’t orderable anymore. #574
Changes¶
Updated
attr.validators.__all__to include new validators added in #425. #517Slotted classes now use a pure Python mechanism to rewrite the
__class__cell when rebuilding the class, sosuper()works even on environments wherectypesis not installed. #522When collecting attributes using
@attr.s(auto_attribs=True), attributes with a default ofNoneare now deleted too. #523, #556Fixed
attr.validators.deep_iterable()andattr.validators.deep_mapping()type stubs. #533attr.validators.is_callable()validator now raises an exceptionattr.exceptions.NotCallableError, a subclass ofTypeError, informing the received value. #536@attr.s(auto_exc=True)now generates classes that are hashable by ID, as the documentation always claimed it would. #543, #563Added
attr.validators.matches_re()that checks string attributes whether they match a regular expression. #552Keyword-only attributes (
kw_only=True) and attributes that are excluded from theattrs’s__init__(init=False) now can appear before mandatory attributes. #559The fake filename for generated methods is now more stable. It won’t change when you restart the process. #560
The value passed to
@attr.ib(repr=…)can now be either a boolean (as before) or a callable. That callable must return a string and is then used for formatting the attribute by the generated__repr__()method. #568Added
attr.__version_info__that can be used to reliably check the version ofattrsand write forward- and backward-compatible code. Please check out the section on deprecated APIs on how to use it. #580
19.1.0 (2019-03-03)¶
Backward-incompatible Changes¶
Fixed a bug where deserialized objects with
cache_hash=Truecould have incorrect hash code values. This change breaks classes withcache_hash=Truewhen a custom__setstate__is present. An exception will be thrown when applying theattrsannotation to such a class. This limitation is tracked in issue #494. #482
Changes¶
Add
is_callable,deep_iterable, anddeep_mappingvalidators.is_callable: validates that a value is callabledeep_iterable: Allows recursion down into an iterable, applying another validator to every member in the iterable as well as applying an optional validator to the iterable itself.deep_mapping: Allows recursion down into the items in a mapping object, applying a key validator and a value validator to the key and value in every item. Also applies an optional validator to the mapping object itself.
You can find them in the
attr.validatorspackage. #425Fixed stub files to prevent errors raised by mypy’s
disallow_any_generics = Trueoption. #443Attributes with
init=Falsenow can follow afterkw_only=Trueattributes. #450attrsnow has first class support for defining exception classes.If you define a class using
@attr.s(auto_exc=True)and subclass an exception, the class will behave like a well-behaved exception class including an appropriate__str__method, and all attributes additionally available in anargsattribute. #500Clarified documentation for hashing to warn that hashable objects should be deeply immutable (in their usage, even if this is not enforced). #503
18.2.0 (2018-09-01)¶
Deprecations¶
Comparing subclasses using
<,>,<=, and>=is now deprecated. The docs always claimed that instances are only compared if the types are identical, so this is a first step to conform to the docs.Equality operators (
==and!=) were always strict in this regard. #394
Changes¶
attrsnow ships its own PEP 484 type hints. Together with mypy’sattrsplugin, you’ve got all you need for writing statically typed code in both Python 2 and 3!At that occasion, we’ve also added narrative docs about type annotations in
attrs. #238Added kw_only arguments to
attr.ibandattr.s, and a corresponding kw_only attribute toattr.Attribute. This change makes it possible to have a generated__init__with keyword-only arguments on Python 3, relaxing the required ordering of default and non-default valued attributes. #281, #411The test suite now runs with
hypothesis.HealthCheck.too_slowdisabled to prevent CI breakage on slower computers. #364, #396attr.validators.in_()now raises aValueErrorwith a useful message even if the options are a string and the value is not a string. #383attr.asdict()now properly handles deeply nested lists and dictionaries. #395Added
attr.converters.default_if_none()that allows to replaceNonevalues in attributes. For exampleattr.ib(converter=default_if_none(""))replacesNoneby empty strings. #400, #414Fixed a reference leak where the original class would remain live after being replaced when
slots=Trueis set. #407Slotted classes can now be made weakly referenceable by passing
@attr.s(weakref_slot=True). #420Added cache_hash option to
@attr.swhich causes the hash code to be computed once and stored on the object. #426Attributes can be named
propertyanditemgetternow. #430It is now possible to override a base class’ class variable using only class annotations. #431
18.1.0 (2018-05-03)¶
Changes¶
x=X(); x.cycle = x; repr(x)will no longer raise aRecursionError, and will instead show asX(x=...).attr.ib(factory=f)is now syntactic sugar for the common case ofattr.ib(default=attr.Factory(f)).Added
attr.field_dict()to return an ordered dictionary ofattrsattributes for a class, whose keys are the attribute names.The order of attributes that are passed into
attr.make_class()or the these argument of@attr.s()is now retained if the dictionary is ordered (i.e.dicton Python 3.6 and later,collections.OrderedDictotherwise).Before, the order was always determined by the order in which the attributes have been defined which may not be desirable when creating classes programatically.
In slotted classes,
__getstate__and__setstate__now ignore the__weakref__attribute.Setting the cell type is now completely best effort. This fixes
attrson Jython.We cannot make any guarantees regarding Jython though, because our test suite cannot run due to dependency incompatabilities.
If
attr.sis passed a these argument, it will no longer attempt to remove attributes with the same name from the class body.The hash of
attr.NOTHINGis now vegan and faster on 32bit Python builds.The overhead of instantiating frozen dict classes is virtually eliminated. #336
Generated
__init__methods now have an__annotations__attribute derived from the types of the fields.We have restructured the documentation a bit to account for
attrs’ growth in scope. Instead of putting everything into the examples page, we have started to extract narrative chapters.So far, we’ve added chapters on initialization and hashing.
Expect more to come!
17.4.0 (2017-12-30)¶
Backward-incompatible Changes¶
The traversal of MROs when using multiple inheritance was backward: If you defined a class
Cthat subclassesAandBlikeC(A, B),attrswould have collected the attributes fromBbefore those ofA.This is now fixed and means that in classes that employ multiple inheritance, the output of
__repr__and the order of positional arguments in__init__changes. Because of the nature of this bug, a proper deprecation cycle was unfortunately impossible.Generally speaking, it’s advisable to prefer
kwargs-based initialization anyways – especially if you employ multiple inheritance and diamond-shaped hierarchies.The
__repr__set byattrsno longer produces anAttributeErrorwhen the instance is missing some of the specified attributes (either through deleting or after usinginit=Falseon some attributes).This can break code that relied on
repr(attr_cls_instance)raisingAttributeErrorto check if anyattrs-specified members were unset.If you were using this, you can implement a custom method for checking this:
def has_unset_members(self): for field in attr.fields(type(self)): try: getattr(self, field.name) except AttributeError: return True return False
Deprecations¶
The
attr.ib(convert=callable)option is now deprecated in favor ofattr.ib(converter=callable).This is done to achieve consistency with other noun-based arguments like validator.
convert will keep working until at least January 2019 while raising a
DeprecationWarning.
Changes¶
Generated
__hash__methods now hash the class type along with the attribute values. Until now the hashes of two classes with the same values were identical which was a bug.The generated method is also much faster now.
attr.ib’s metadata argument now defaults to a unique emptydictinstance instead of sharing a common emptydictfor all. The singleton emptydictis still enforced.ctypesis optional now however if it’s missing, a baresuper()will not work in slotted classes. This should only happen in special environments like Google App Engine.The attribute redefinition feature introduced in 17.3.0 now takes into account if an attribute is redefined via multiple inheritance. In that case, the definition that is closer to the base of the class hierarchy wins.
Subclasses of
auto_attribs=Truecan be empty now.Equality tests are much faster now.
All generated methods now have correct
__module__,__name__, and (on Python 3)__qualname__attributes.
17.3.0 (2017-11-08)¶
Backward-incompatible Changes¶
Attributes are no longer defined on the class body.
This means that if you define a class
Cwith an attributex, the class will not have an attributexfor introspection. Instead ofC.x, useattr.fields(C).xor look atC.__attrs_attrs__. The old behavior has been deprecated since version 16.1. (#253)
Changes¶
super()and__class__now work with slotted classes on Python 3. (#102, #226, #269, #270, #272)Added type argument to
attr.ib()and correspondingtypeattribute toattr.Attribute.This change paves the way for automatic type checking and serialization (though as of this release
attrsdoes not make use of it). In Python 3.6 or higher, the value ofattr.Attribute.typecan alternately be set using variable type annotations (see PEP 526). (#151, #214, #215, #239)The combination of
str=Trueandslots=Truenow works on Python 2. (#198)attr.Factoryis hashable again. (#204)Subclasses now can overwrite attribute definitions of their base classes.
That means that you can – for example – change the default value for an attribute by redefining it. (#221, #229)
Added new option auto_attribs to
@attr.sthat allows to collect annotated fields without setting them toattr.ib().Setting a field to an
attr.ib()is still possible to supply options like validators. Setting it to any other value is treated like it was passed asattr.ib(default=value)– passing an instance ofattr.Factoryalso works as expected. (#262, #277)Instances of classes created using
attr.make_class()can now be pickled. (#282)
17.2.0 (2017-05-24)¶
17.1.0 (2017-05-16)¶
To encourage more participation, the project has also been moved into a dedicated GitHub organization and everyone is most welcome to join!
attrs also has a logo now!
Backward-incompatible Changes:¶
attrswill set the__hash__()method toNoneby default now. The way hashes were handled before was in conflict with Python’s specification. This may break some software although this breakage is most likely just surfacing of latent bugs. You can always makeattrscreate the__hash__()method using@attr.s(hash=True). See #136 for the rationale of this change.Warning
Please do not upgrade blindly and do test your software! Especially if you use instances as dict keys or put them into sets!
Correspondingly,
attr.ib’s hash argument isNoneby default too and mirrors the cmp argument as it should.
Deprecations:¶
attr.assoc()is now deprecated in favor ofattr.evolve()and will stop working in 2018.
Changes:¶
Fix default hashing behavior. Now hash mirrors the value of cmp and classes are unhashable by default. #136 #142
Added
attr.evolve()that, given an instance of anattrsclass and field changes as keyword arguments, will instantiate a copy of the given instance with the changes applied.evolve()replacesassoc(), which is now deprecated.evolve()is significantly faster thanassoc(), and requires the class have an initializer that can take the field values as keyword arguments (likeattrsitself can generate). #116 #124 #135FrozenInstanceErroris now raised when trying to delete an attribute from a frozen class. #118Frozen-ness of classes is now inherited. #128
__attrs_post_init__()is now run if validation is disabled. #130Added
attr.validators.in_(options)that, given the allowedoptions, checks whether the attribute value is in it. This can be used to check constants, enums, mappings, etc. #181Added
attr.validators.and_()that composes multiple validators into one. #161For convenience, the validator argument of
@attr.snow can take a list of validators that are wrapped usingand_(). #138Accordingly,
attr.validators.optional()now can take a list of validators too. #161Validators can now be defined conveniently inline by using the attribute as a decorator. Check out the validator examples to see it in action! #143
attr.Factory()now has a takes_self argument that makes the initializer to pass the partially initialized instance into the factory. In other words you can define attribute defaults based on other attributes. #165 #189Default factories can now also be defined inline using decorators. They are always passed the partially initialized instance. #165
Conversion can now be made optional using
attr.converters.optional(). #105 #173attr.make_class()now accepts the keyword argumentbaseswhich allows for subclassing. #152Metaclasses are now preserved with
slots=True. #155
16.3.0 (2016-11-24)¶
Changes:¶
Attributes now can have user-defined metadata which greatly improves
attrs’s extensibility. #96Allow for a
__attrs_post_init__()method that – if defined – will get called at the end of theattrs-generated__init__()method. #111Added
@attr.s(str=True)that will optionally create a__str__()method that is identical to__repr__(). This is mainly useful withExceptions and other classes that rely on a useful__str__()implementation but overwrite the default one through a poor own one. Default Python class behavior is to use__repr__()as__str__()anyways.If you tried using
attrswithExceptions and were puzzled by the tracebacks: this option is for you.__name__is no longer overwritten with__qualname__forattr.s(slots=True)classes. #99
16.2.0 (2016-09-17)¶
Changes:¶
Added
attr.astuple()that – similarly toattr.asdict()– returns the instance as a tuple. #77Converters now work with frozen classes. #76
Instantiation of
attrsclasses with converters is now significantly faster. #80Pickling now works with slotted classes. #81
attr.assoc()now works with slotted classes. #84The tuple returned by
attr.fields()now also allows to access theAttributeinstances by name. Yes, we’ve subclassedtupleso you don’t have to! Thereforeattr.fields(C).xis equivalent to the deprecatedC.xand works with slotted classes. #88
16.1.0 (2016-08-30)¶
Backward-incompatible Changes:¶
All instances where function arguments were called
clhave been changed to the more Pythoniccls. Since it was always the first argument, it’s doubtful anyone ever called those function with in the keyword form. If so, sorry for any breakage but there’s no practical deprecation path to solve this ugly wart.
Deprecations:¶
Accessing
Attributeinstances on class objects is now deprecated and will stop working in 2017. If you need introspection please use the__attrs_attrs__attribute or theattr.fields()function that carry them too. In the future, the attributes that are defined on the class body and are usually overwritten in your__init__method are simply removed after@attr.shas been applied.This will remove the confusing error message if you write your own
__init__and forget to initialize some attribute. Instead you will get a straightforwardAttributeError. In other words: decorated classes will work more like plain Python classes which was alwaysattrs’s goal.The serious business aliases
attr.attributesandattr.attrhave been deprecated in favor ofattr.attrsandattr.attribwhich are much more consistent and frankly obvious in hindsight. They will be purged from documentation immediately but there are no plans to actually remove them.
Changes:¶
attr.asdict()‘sdict_factoryarguments is now propagated on recursion. #45attr.asdict(),attr.has()andattr.fields()are significantly faster. #48 #51Add
attr.attrsandattr.attribas a more consistent aliases forattr.sandattr.ib.Add frozen option to
attr.sthat will make instances best-effort immutable. #60attr.asdict()now takesretain_collection_typesas an argument. IfTrue, it does not convert attributes of typetupleorsettolist. #69
16.0.0 (2016-05-23)¶
Backward-incompatible Changes:¶
Python 3.3 and 2.6 are no longer supported. They may work by chance but any effort to keep them working has ceased.
The last Python 2.6 release was on October 29, 2013 and is no longer supported by the CPython core team. Major Python packages like Django and Twisted dropped Python 2.6 a while ago already.
Python 3.3 never had a significant user base and wasn’t part of any distribution’s LTS release.
Changes:¶
__slots__have arrived! Classes now can automatically be slotted-style (and save your precious memory) just by passingslots=True. #35Allow the case of initializing attributes that are set to
init=False. This allows for clean initializer parameter lists while being able to initialize attributes to default values. #32attr.asdict()can now produce arbitrary mappings instead of Pythondicts when provided with adict_factoryargument. #40Multiple performance improvements.