2023-01-13 02:28:26 +00:00
|
|
|
# SPDX-License-Identifier: MIT
|
|
|
|
|
2023-01-12 01:04:47 +00:00
|
|
|
"""
|
|
|
|
Commonly useful filters for `attr.asdict`.
|
|
|
|
"""
|
|
|
|
|
|
|
|
from ._make import Attribute
|
|
|
|
|
|
|
|
|
|
|
|
def _split_what(what):
|
|
|
|
"""
|
|
|
|
Returns a tuple of `frozenset`s of classes and attributes.
|
|
|
|
"""
|
|
|
|
return (
|
2023-01-13 02:28:26 +00:00
|
|
|
frozenset(cls for cls in what if isinstance(cls, type)),
|
2023-10-07 23:21:06 +00:00
|
|
|
frozenset(cls for cls in what if isinstance(cls, str)),
|
2023-01-12 01:04:47 +00:00
|
|
|
frozenset(cls for cls in what if isinstance(cls, Attribute)),
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def include(*what):
|
|
|
|
"""
|
2023-01-13 02:28:26 +00:00
|
|
|
Include *what*.
|
2023-01-12 01:04:47 +00:00
|
|
|
|
2023-01-13 02:28:26 +00:00
|
|
|
:param what: What to include.
|
2023-10-07 23:21:06 +00:00
|
|
|
:type what: `list` of classes `type`, field names `str` or
|
|
|
|
`attrs.Attribute`\\ s
|
2023-01-12 01:04:47 +00:00
|
|
|
|
|
|
|
:rtype: `callable`
|
2023-10-07 23:21:06 +00:00
|
|
|
|
|
|
|
.. versionchanged:: 23.1.0 Accept strings with field names.
|
2023-01-12 01:04:47 +00:00
|
|
|
"""
|
2023-10-07 23:21:06 +00:00
|
|
|
cls, names, attrs = _split_what(what)
|
2023-01-12 01:04:47 +00:00
|
|
|
|
|
|
|
def include_(attribute, value):
|
2023-10-07 23:21:06 +00:00
|
|
|
return (
|
|
|
|
value.__class__ in cls
|
|
|
|
or attribute.name in names
|
|
|
|
or attribute in attrs
|
|
|
|
)
|
2023-01-12 01:04:47 +00:00
|
|
|
|
|
|
|
return include_
|
|
|
|
|
|
|
|
|
|
|
|
def exclude(*what):
|
|
|
|
"""
|
2023-01-13 02:28:26 +00:00
|
|
|
Exclude *what*.
|
2023-01-12 01:04:47 +00:00
|
|
|
|
2023-01-13 02:28:26 +00:00
|
|
|
:param what: What to exclude.
|
2023-10-07 23:21:06 +00:00
|
|
|
:type what: `list` of classes `type`, field names `str` or
|
|
|
|
`attrs.Attribute`\\ s.
|
2023-01-12 01:04:47 +00:00
|
|
|
|
|
|
|
:rtype: `callable`
|
2023-10-07 23:21:06 +00:00
|
|
|
|
|
|
|
.. versionchanged:: 23.3.0 Accept field name string as input argument
|
2023-01-12 01:04:47 +00:00
|
|
|
"""
|
2023-10-07 23:21:06 +00:00
|
|
|
cls, names, attrs = _split_what(what)
|
2023-01-12 01:04:47 +00:00
|
|
|
|
|
|
|
def exclude_(attribute, value):
|
2023-10-07 23:21:06 +00:00
|
|
|
return not (
|
|
|
|
value.__class__ in cls
|
|
|
|
or attribute.name in names
|
|
|
|
or attribute in attrs
|
|
|
|
)
|
2023-01-12 01:04:47 +00:00
|
|
|
|
|
|
|
return exclude_
|