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

Add attr.fields_dict() #349

Merged
merged 3 commits into from
Mar 3, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/290.change.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added ``attr.field_dict()`` to return an ordered dictionary of ``attrs`` attributes for a class, whose keys are the attribute names.
1 change: 1 addition & 0 deletions changelog.d/349.change.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added ``attr.field_dict()`` to return an ordered dictionary of ``attrs`` attributes for a class, whose keys are the attribute names.
17 changes: 17 additions & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,23 @@ Helpers
>>> attr.fields(C).y is attr.fields(C)[1]
True

.. autofunction:: attr.fields_dict

For example:

.. doctest::

>>> @attr.s
... class C(object):
... x = attr.ib()
... y = attr.ib()
>>> attr.fields_dict(C)
{'x': Attribute(name='x', default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None), 'y': Attribute(name='y', default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None)}
>>> attr.fields_dict(C)['y']
Attribute(name='y', default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None)
>>> attr.fields_dict(C)['y'] is attr.fields(C).y
True


.. autofunction:: attr.has

Expand Down
4 changes: 3 additions & 1 deletion src/attr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
from ._config import get_run_validators, set_run_validators
from ._funcs import asdict, assoc, astuple, evolve, has
from ._make import (
NOTHING, Attribute, Factory, attrib, attrs, fields, make_class, validate
NOTHING, Attribute, Factory, attrib, attrs, fields, fields_dict,
make_class, validate
)


Expand Down Expand Up @@ -43,6 +44,7 @@
"evolve",
"exceptions",
"fields",
"fields_dict",
"filters",
"get_run_validators",
"has",
Expand Down
30 changes: 29 additions & 1 deletion src/attr/_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -1042,7 +1042,7 @@ def _add_init(cls, frozen):

def fields(cls):
"""
Returns the tuple of ``attrs`` attributes for a class.
Return the tuple of ``attrs`` attributes for a class.

The tuple also allows accessing the fields by their names (see below for
examples).
Expand All @@ -1068,6 +1068,34 @@ def fields(cls):
return attrs


def fields_dict(cls):
"""
Return an ordered dictionary of ``attrs`` attributes for a class, whose
keys are the attribute names.

:param type cls: Class to introspect.

:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.

:rtype: an ordered dict where keys are attribute names and values are
:class:`attr.Attribute`\ s. This will be a :class:`dict` if it's
naturally ordered like on Python 3.6+ or an
:class:`~collections.OrderedDict` otherwise.

.. versionadded:: 18.1.0
"""
if not isclass(cls):
raise TypeError("Passed object must be a class.")
attrs = getattr(cls, "__attrs_attrs__", None)
if attrs is None:
raise NotAnAttrsClassError(
"{cls!r} is not an attrs-decorated class.".format(cls=cls)
)
return ordered_dict(((a.name, a) for a in attrs))


def validate(inst):
"""
Validate all attributes on *inst* that have a validator.
Expand Down
40 changes: 39 additions & 1 deletion tests/test_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
from attr._compat import PY2, ordered_dict
from attr._make import (
Attribute, Factory, _AndValidator, _Attributes, _ClassBuilder,
_CountingAttr, _transform_attrs, and_, fields, make_class, validate
_CountingAttr, _transform_attrs, and_, fields, fields_dict, make_class,
validate
)
from attr.exceptions import DefaultAlreadySetError, NotAnAttrsClassError

Expand Down Expand Up @@ -656,6 +657,7 @@ def test_handler_non_attrs_class(self, C):
"""
with pytest.raises(NotAnAttrsClassError) as e:
fields(object)

assert (
"{o!r} is not an attrs-decorated class.".format(o=object)
) == e.value.args[0]
Expand All @@ -676,6 +678,42 @@ def test_fields_properties(self, C):
assert getattr(fields(C), attribute.name) is attribute


class TestFieldsDict(object):
"""
Tests for `fields_dict`.
"""
def test_instance(self, C):
"""
Raises `TypeError` on non-classes.
"""
with pytest.raises(TypeError) as e:
fields_dict(C(1, 2))

assert "Passed object must be a class." == e.value.args[0]

def test_handler_non_attrs_class(self, C):
"""
Raises `ValueError` if passed a non-``attrs`` instance.
"""
with pytest.raises(NotAnAttrsClassError) as e:
fields_dict(object)

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.


assert (
"{o!r} is not an attrs-decorated class.".format(o=object)
) == e.value.args[0]

@given(simple_classes())
def test_fields_dict(self, C):
"""
Returns an ordered dict of ``{attribute_name: Attribute}``.
"""
d = fields_dict(C)

assert isinstance(d, ordered_dict)
assert list(fields(C)) == list(d.values())
assert [a.name for a in fields(C)] == [field_name for field_name in d]


class TestConverter(object):
"""
Tests for attribute conversion.
Expand Down