attrs/attr/filters.py

54 lines
1.1 KiB
Python
Raw Normal View History

2015-02-20 15:34:21 +00:00
"""
Commonly useful filters for :func:`attr.asdict`.
"""
from __future__ import absolute_import, division, print_function
2015-03-23 13:04:05 +00:00
import inspect
2015-02-20 15:34:21 +00:00
from ._make import Attribute
def _split_what(what):
"""
Returns a tuple of `frozenset`s of classes and attributes.
"""
return (
2015-03-23 13:04:05 +00:00
frozenset(cl for cl in what if inspect.isclass(cl)),
2015-02-20 15:34:21 +00:00
frozenset(cl for cl in what if isinstance(cl, Attribute)),
)
def include(*what):
"""
Whitelist *what*.
:param what: What to whitelist.
:type what: :class:`list` of :class:`type` or :class:`attr.Attribute` s.
:rtype: :class:`callable`
"""
cls, attrs = _split_what(what)
def include_(attribute, value):
return value.__class__ in cls or attribute in attrs
return include_
def exclude(*what):
"""
Blacklist *what*.
:param what: What to blacklist.
2015-03-23 13:04:05 +00:00
:type what: :class:`list` of classes or :class:`attr.Attribute` s.
2015-02-20 15:34:21 +00:00
:rtype: :class:`callable`
"""
cls, attrs = _split_what(what)
def exclude_(attribute, value):
return value.__class__ not in cls and attribute not in attrs
return exclude_