Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/attr/_funcs.py: 20%
116 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:51 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:51 +0000
1# SPDX-License-Identifier: MIT
4import copy
6from ._compat import PY_3_9_PLUS, get_generic_base
7from ._make import NOTHING, _obj_setattr, fields
8from .exceptions import AttrsAttributeNotFoundError
11def asdict(
12 inst,
13 recurse=True,
14 filter=None,
15 dict_factory=dict,
16 retain_collection_types=False,
17 value_serializer=None,
18):
19 """
20 Return the *attrs* attribute values of *inst* as a dict.
22 Optionally recurse into other *attrs*-decorated classes.
24 :param inst: Instance of an *attrs*-decorated class.
25 :param bool recurse: Recurse into classes that are also
26 *attrs*-decorated.
27 :param callable filter: A callable whose return code determines whether an
28 attribute or element is included (``True``) or dropped (``False``). Is
29 called with the `attrs.Attribute` as the first argument and the
30 value as the second argument.
31 :param callable dict_factory: A callable to produce dictionaries from. For
32 example, to produce ordered dictionaries instead of normal Python
33 dictionaries, pass in ``collections.OrderedDict``.
34 :param bool retain_collection_types: Do not convert to ``list`` when
35 encountering an attribute whose type is ``tuple`` or ``set``. Only
36 meaningful if ``recurse`` is ``True``.
37 :param Optional[callable] value_serializer: A hook that is called for every
38 attribute or dict key/value. It receives the current instance, field
39 and value and must return the (updated) value. The hook is run *after*
40 the optional *filter* has been applied.
42 :rtype: return type of *dict_factory*
44 :raise attrs.exceptions.NotAnAttrsClassError: If *cls* is not an *attrs*
45 class.
47 .. versionadded:: 16.0.0 *dict_factory*
48 .. versionadded:: 16.1.0 *retain_collection_types*
49 .. versionadded:: 20.3.0 *value_serializer*
50 .. versionadded:: 21.3.0 If a dict has a collection for a key, it is
51 serialized as a tuple.
52 """
53 attrs = fields(inst.__class__)
54 rv = dict_factory()
55 for a in attrs:
56 v = getattr(inst, a.name)
57 if filter is not None and not filter(a, v):
58 continue
60 if value_serializer is not None:
61 v = value_serializer(inst, a, v)
63 if recurse is True:
64 if has(v.__class__):
65 rv[a.name] = asdict(
66 v,
67 recurse=True,
68 filter=filter,
69 dict_factory=dict_factory,
70 retain_collection_types=retain_collection_types,
71 value_serializer=value_serializer,
72 )
73 elif isinstance(v, (tuple, list, set, frozenset)):
74 cf = v.__class__ if retain_collection_types is True else list
75 rv[a.name] = cf(
76 [
77 _asdict_anything(
78 i,
79 is_key=False,
80 filter=filter,
81 dict_factory=dict_factory,
82 retain_collection_types=retain_collection_types,
83 value_serializer=value_serializer,
84 )
85 for i in v
86 ]
87 )
88 elif isinstance(v, dict):
89 df = dict_factory
90 rv[a.name] = df(
91 (
92 _asdict_anything(
93 kk,
94 is_key=True,
95 filter=filter,
96 dict_factory=df,
97 retain_collection_types=retain_collection_types,
98 value_serializer=value_serializer,
99 ),
100 _asdict_anything(
101 vv,
102 is_key=False,
103 filter=filter,
104 dict_factory=df,
105 retain_collection_types=retain_collection_types,
106 value_serializer=value_serializer,
107 ),
108 )
109 for kk, vv in v.items()
110 )
111 else:
112 rv[a.name] = v
113 else:
114 rv[a.name] = v
115 return rv
118def _asdict_anything(
119 val,
120 is_key,
121 filter,
122 dict_factory,
123 retain_collection_types,
124 value_serializer,
125):
126 """
127 ``asdict`` only works on attrs instances, this works on anything.
128 """
129 if getattr(val.__class__, "__attrs_attrs__", None) is not None:
130 # Attrs class.
131 rv = asdict(
132 val,
133 recurse=True,
134 filter=filter,
135 dict_factory=dict_factory,
136 retain_collection_types=retain_collection_types,
137 value_serializer=value_serializer,
138 )
139 elif isinstance(val, (tuple, list, set, frozenset)):
140 if retain_collection_types is True:
141 cf = val.__class__
142 elif is_key:
143 cf = tuple
144 else:
145 cf = list
147 rv = cf(
148 [
149 _asdict_anything(
150 i,
151 is_key=False,
152 filter=filter,
153 dict_factory=dict_factory,
154 retain_collection_types=retain_collection_types,
155 value_serializer=value_serializer,
156 )
157 for i in val
158 ]
159 )
160 elif isinstance(val, dict):
161 df = dict_factory
162 rv = df(
163 (
164 _asdict_anything(
165 kk,
166 is_key=True,
167 filter=filter,
168 dict_factory=df,
169 retain_collection_types=retain_collection_types,
170 value_serializer=value_serializer,
171 ),
172 _asdict_anything(
173 vv,
174 is_key=False,
175 filter=filter,
176 dict_factory=df,
177 retain_collection_types=retain_collection_types,
178 value_serializer=value_serializer,
179 ),
180 )
181 for kk, vv in val.items()
182 )
183 else:
184 rv = val
185 if value_serializer is not None:
186 rv = value_serializer(None, None, rv)
188 return rv
191def astuple(
192 inst,
193 recurse=True,
194 filter=None,
195 tuple_factory=tuple,
196 retain_collection_types=False,
197):
198 """
199 Return the *attrs* attribute values of *inst* as a tuple.
201 Optionally recurse into other *attrs*-decorated classes.
203 :param inst: Instance of an *attrs*-decorated class.
204 :param bool recurse: Recurse into classes that are also
205 *attrs*-decorated.
206 :param callable filter: A callable whose return code determines whether an
207 attribute or element is included (``True``) or dropped (``False``). Is
208 called with the `attrs.Attribute` as the first argument and the
209 value as the second argument.
210 :param callable tuple_factory: A callable to produce tuples from. For
211 example, to produce lists instead of tuples.
212 :param bool retain_collection_types: Do not convert to ``list``
213 or ``dict`` when encountering an attribute which type is
214 ``tuple``, ``dict`` or ``set``. Only meaningful if ``recurse`` is
215 ``True``.
217 :rtype: return type of *tuple_factory*
219 :raise attrs.exceptions.NotAnAttrsClassError: If *cls* is not an *attrs*
220 class.
222 .. versionadded:: 16.2.0
223 """
224 attrs = fields(inst.__class__)
225 rv = []
226 retain = retain_collection_types # Very long. :/
227 for a in attrs:
228 v = getattr(inst, a.name)
229 if filter is not None and not filter(a, v):
230 continue
231 if recurse is True:
232 if has(v.__class__):
233 rv.append(
234 astuple(
235 v,
236 recurse=True,
237 filter=filter,
238 tuple_factory=tuple_factory,
239 retain_collection_types=retain,
240 )
241 )
242 elif isinstance(v, (tuple, list, set, frozenset)):
243 cf = v.__class__ if retain is True else list
244 rv.append(
245 cf(
246 [
247 astuple(
248 j,
249 recurse=True,
250 filter=filter,
251 tuple_factory=tuple_factory,
252 retain_collection_types=retain,
253 )
254 if has(j.__class__)
255 else j
256 for j in v
257 ]
258 )
259 )
260 elif isinstance(v, dict):
261 df = v.__class__ if retain is True else dict
262 rv.append(
263 df(
264 (
265 astuple(
266 kk,
267 tuple_factory=tuple_factory,
268 retain_collection_types=retain,
269 )
270 if has(kk.__class__)
271 else kk,
272 astuple(
273 vv,
274 tuple_factory=tuple_factory,
275 retain_collection_types=retain,
276 )
277 if has(vv.__class__)
278 else vv,
279 )
280 for kk, vv in v.items()
281 )
282 )
283 else:
284 rv.append(v)
285 else:
286 rv.append(v)
288 return rv if tuple_factory is list else tuple_factory(rv)
291def has(cls):
292 """
293 Check whether *cls* is a class with *attrs* attributes.
295 :param type cls: Class to introspect.
296 :raise TypeError: If *cls* is not a class.
298 :rtype: bool
299 """
300 attrs = getattr(cls, "__attrs_attrs__", None)
301 if attrs is not None:
302 return True
304 # No attrs, maybe it's a specialized generic (A[str])?
305 generic_base = get_generic_base(cls)
306 if generic_base is not None:
307 generic_attrs = getattr(generic_base, "__attrs_attrs__", None)
308 if generic_attrs is not None:
309 # Stick it on here for speed next time.
310 cls.__attrs_attrs__ = generic_attrs
311 return generic_attrs is not None
312 return False
315def assoc(inst, **changes):
316 """
317 Copy *inst* and apply *changes*.
319 This is different from `evolve` that applies the changes to the arguments
320 that create the new instance.
322 `evolve`'s behavior is preferable, but there are `edge cases`_ where it
323 doesn't work. Therefore `assoc` is deprecated, but will not be removed.
325 .. _`edge cases`: https://github.com/python-attrs/attrs/issues/251
327 :param inst: Instance of a class with *attrs* attributes.
328 :param changes: Keyword changes in the new copy.
330 :return: A copy of inst with *changes* incorporated.
332 :raise attrs.exceptions.AttrsAttributeNotFoundError: If *attr_name*
333 couldn't be found on *cls*.
334 :raise attrs.exceptions.NotAnAttrsClassError: If *cls* is not an *attrs*
335 class.
337 .. deprecated:: 17.1.0
338 Use `attrs.evolve` instead if you can.
339 This function will not be removed du to the slightly different approach
340 compared to `attrs.evolve`.
341 """
342 new = copy.copy(inst)
343 attrs = fields(inst.__class__)
344 for k, v in changes.items():
345 a = getattr(attrs, k, NOTHING)
346 if a is NOTHING:
347 raise AttrsAttributeNotFoundError(
348 f"{k} is not an attrs attribute on {new.__class__}."
349 )
350 _obj_setattr(new, k, v)
351 return new
354def evolve(*args, **changes):
355 """
356 Create a new instance, based on the first positional argument with
357 *changes* applied.
359 :param inst: Instance of a class with *attrs* attributes.
360 :param changes: Keyword changes in the new copy.
362 :return: A copy of inst with *changes* incorporated.
364 :raise TypeError: If *attr_name* couldn't be found in the class
365 ``__init__``.
366 :raise attrs.exceptions.NotAnAttrsClassError: If *cls* is not an *attrs*
367 class.
369 .. versionadded:: 17.1.0
370 .. deprecated:: 23.1.0
371 It is now deprecated to pass the instance using the keyword argument
372 *inst*. It will raise a warning until at least April 2024, after which
373 it will become an error. Always pass the instance as a positional
374 argument.
375 """
376 # Try to get instance by positional argument first.
377 # Use changes otherwise and warn it'll break.
378 if args:
379 try:
380 (inst,) = args
381 except ValueError:
382 raise TypeError(
383 f"evolve() takes 1 positional argument, but {len(args)} "
384 "were given"
385 ) from None
386 else:
387 try:
388 inst = changes.pop("inst")
389 except KeyError:
390 raise TypeError(
391 "evolve() missing 1 required positional argument: 'inst'"
392 ) from None
394 import warnings
396 warnings.warn(
397 "Passing the instance per keyword argument is deprecated and "
398 "will stop working in, or after, April 2024.",
399 DeprecationWarning,
400 stacklevel=2,
401 )
403 cls = inst.__class__
404 attrs = fields(cls)
405 for a in attrs:
406 if not a.init:
407 continue
408 attr_name = a.name # To deal with private attributes.
409 init_name = a.alias
410 if init_name not in changes:
411 changes[init_name] = getattr(inst, attr_name)
413 return cls(**changes)
416def resolve_types(
417 cls, globalns=None, localns=None, attribs=None, include_extras=True
418):
419 """
420 Resolve any strings and forward annotations in type annotations.
422 This is only required if you need concrete types in `Attribute`'s *type*
423 field. In other words, you don't need to resolve your types if you only
424 use them for static type checking.
426 With no arguments, names will be looked up in the module in which the class
427 was created. If this is not what you want, e.g. if the name only exists
428 inside a method, you may pass *globalns* or *localns* to specify other
429 dictionaries in which to look up these names. See the docs of
430 `typing.get_type_hints` for more details.
432 :param type cls: Class to resolve.
433 :param Optional[dict] globalns: Dictionary containing global variables.
434 :param Optional[dict] localns: Dictionary containing local variables.
435 :param Optional[list] attribs: List of attribs for the given class.
436 This is necessary when calling from inside a ``field_transformer``
437 since *cls* is not an *attrs* class yet.
438 :param bool include_extras: Resolve more accurately, if possible.
439 Pass ``include_extras`` to ``typing.get_hints``, if supported by the
440 typing module. On supported Python versions (3.9+), this resolves the
441 types more accurately.
443 :raise TypeError: If *cls* is not a class.
444 :raise attrs.exceptions.NotAnAttrsClassError: If *cls* is not an *attrs*
445 class and you didn't pass any attribs.
446 :raise NameError: If types cannot be resolved because of missing variables.
448 :returns: *cls* so you can use this function also as a class decorator.
449 Please note that you have to apply it **after** `attrs.define`. That
450 means the decorator has to come in the line **before** `attrs.define`.
452 .. versionadded:: 20.1.0
453 .. versionadded:: 21.1.0 *attribs*
454 .. versionadded:: 23.1.0 *include_extras*
456 """
457 # Since calling get_type_hints is expensive we cache whether we've
458 # done it already.
459 if getattr(cls, "__attrs_types_resolved__", None) != cls:
460 import typing
462 kwargs = {"globalns": globalns, "localns": localns}
464 if PY_3_9_PLUS:
465 kwargs["include_extras"] = include_extras
467 hints = typing.get_type_hints(cls, **kwargs)
468 for field in fields(cls) if attribs is None else attribs:
469 if field.name in hints:
470 # Since fields have been frozen we must work around it.
471 _obj_setattr(field, "type", hints[field.name])
472 # We store the class we resolved so that subclasses know they haven't
473 # been resolved.
474 cls.__attrs_types_resolved__ = cls
476 # Return the class so you can use it as a decorator too.
477 return cls