Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/attr/filters.py: 36%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# SPDX-License-Identifier: MIT
3"""
4Commonly useful filters for `attrs.asdict` and `attrs.astuple`.
5"""
7from ._make import Attribute
10def _split_what(what):
11 """
12 Returns a tuple of `frozenset`s of classes and attributes.
13 """
14 return (
15 frozenset(cls for cls in what if isinstance(cls, type)),
16 frozenset(cls for cls in what if isinstance(cls, str)),
17 frozenset(cls for cls in what if isinstance(cls, Attribute)),
18 )
21def include(*what):
22 """
23 Create a filter that only allows *what*.
25 Args:
26 what (list[type, str, attrs.Attribute]):
27 What to include. Can be a type, a name, or an attribute.
29 Returns:
30 Callable:
31 A callable that can be passed to `attrs.asdict`'s and
32 `attrs.astuple`'s *filter* argument.
34 .. versionchanged:: 23.1.0 Accept strings with field names.
35 """
36 cls, names, attrs = _split_what(what)
38 def include_(attribute, value):
39 return (
40 value.__class__ in cls
41 or attribute.name in names
42 or attribute in attrs
43 )
45 return include_
48def exclude(*what):
49 """
50 Create a filter that does **not** allow *what*.
52 Args:
53 what (list[type, str, attrs.Attribute]):
54 What to exclude. Can be a type, a name, or an attribute.
56 Returns:
57 Callable:
58 A callable that can be passed to `attrs.asdict`'s and
59 `attrs.astuple`'s *filter* argument.
61 .. versionchanged:: 23.3.0 Accept field name string as input argument
62 """
63 cls, names, attrs = _split_what(what)
65 def exclude_(attribute, value):
66 return not (
67 value.__class__ in cls
68 or attribute.name in names
69 or attribute in attrs
70 )
72 return exclude_