Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

converters: allow wrapping and passing self and fields #1267

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
1 change: 1 addition & 0 deletions changelog.d/1267.change.md
@@ -0,0 +1 @@
It is now possible to wrap a converter into an `attrs.Converter` and get the current instance and/or the current field definition passed into the converter callable.
21 changes: 21 additions & 0 deletions docs/api.rst
Expand Up @@ -607,6 +607,27 @@ Validators can be both globally and locally disabled:
Converters
----------

.. autoclass:: attrs.Converter

For example:

.. doctest::

>>> def complicated(value, self_, field):
... return int(value) * self_.factor + field.metadata["offset"]
>>> @define
... class C:
... factor = 5 # not an *attrs* field
... x = field(
... metadata={"offset": 200},
... converter=attrs.Converter(
... complicated,
... takes_self=True, takes_field=True
... ))
>>> C("42")
C(x=410)


.. module:: attrs.converters

All objects from ``attrs.converters`` are also available from ``attr.converters`` (it's the same module in a different namespace).
Expand Down
2 changes: 2 additions & 0 deletions src/attr/__init__.py
Expand Up @@ -15,6 +15,7 @@
from ._make import (
NOTHING,
Attribute,
Converter,
Factory,
attrib,
attrs,
Expand All @@ -39,6 +40,7 @@ class AttrsInstance(Protocol):
__all__ = [
"Attribute",
"AttrsInstance",
"Converter",
"Factory",
"NOTHING",
"asdict",
Expand Down