Rename skip to filter and reverse logic

This commit is contained in:
Hynek Schlawack 2015-02-06 14:56:02 +01:00
parent 850915dc47
commit ddf0256527
3 changed files with 13 additions and 12 deletions

View File

@ -30,7 +30,7 @@ def fields(cl):
return copy.deepcopy(attrs)
def asdict(inst, recurse=True, skip=None):
def asdict(inst, recurse=True, filter=None):
"""
Return the ``attrs`` attribute values of *i* as a dict. Optionally recurse
into other ``attrs``-decorated classes.
@ -40,10 +40,11 @@ def asdict(inst, recurse=True, skip=None):
:param recurse: Recurse into classes that are also ``attrs``-decorated.
:type recurse: bool
:param skip: A filter function that causes elements to be left out if it
returns ``True``. Is called with the :class:`attr.Attribute` as the
first argument and the value as the second argument.
:type skip: callable
:param filter: A callable whose return code deteremines whether an
attribute or element is included (``True``) or dropped (``False``). Is
called with the :class:`attr.Attribute` as the first argument and the
value as the second argument.
:type filer: callable
:rtype: :class:`dict`
"""
@ -51,14 +52,14 @@ def asdict(inst, recurse=True, skip=None):
rv = {}
for a in attrs:
v = getattr(inst, a.name)
if skip is not None and skip(a, v):
if filter is not None and not filter(a, v):
continue
if recurse is True:
if has(v.__class__):
rv[a.name] = asdict(v, recurse=True, skip=skip)
rv[a.name] = asdict(v, recurse=True, filter=filter)
elif isinstance(v, (tuple, list, set)):
rv[a.name] = [
asdict(i, recurse=True, skip=skip)
asdict(i, recurse=True, filter=filter)
if has(i.__class__) else i
for i in v
]

View File

@ -73,7 +73,7 @@ When you have a class with data, it often is very convenient to transform that c
{'y': 2, 'x': 1}
Some fields cannot or should not be transformed.
For that, :func:`attr.asdict` offers a callback that decides whether an attribute should be skipped:
For that, :func:`attr.asdict` offers a callback that decides whether an attribute should be included:
.. doctest::
@ -86,7 +86,7 @@ For that, :func:`attr.asdict` offers a callback that decides whether an attribut
... password = attr.ib()
>>> attr.asdict(UserList([User("jane@doe.invalid", "s33kred"),
... User("joe@doe.invalid", "p4ssw0rd")]),
... skip=lambda attr, value: attr.name == "password")
... filter=lambda attr, value: attr.name != "password")
{'users': [{'email': 'jane@doe.invalid'}, {'email': 'joe@doe.invalid'}]}

View File

@ -92,7 +92,7 @@ class TestAsDict(object):
C(3, 4),
))
def test_skip(self):
def test_filter(self):
"""
Attributes that are supposed to be skipped are skipped.
"""
@ -101,7 +101,7 @@ class TestAsDict(object):
} == asdict(C(
C(1, 2),
C(3, 4),
), skip=lambda a, v: a.name == "y")
), filter=lambda a, v: a.name != "y")
@pytest.mark.parametrize("container", [
list,