You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

3124 regels
94 KiB

  1. # SPDX-License-Identifier: MIT
  2. from __future__ import annotations
  3. import abc
  4. import contextlib
  5. import copy
  6. import enum
  7. import inspect
  8. import itertools
  9. import linecache
  10. import sys
  11. import types
  12. import unicodedata
  13. from collections.abc import Callable, Mapping
  14. from functools import cached_property
  15. from typing import Any, NamedTuple, TypeVar
  16. # We need to import _compat itself in addition to the _compat members to avoid
  17. # having the thread-local in the globals here.
  18. from . import _compat, _config, setters
  19. from ._compat import (
  20. PY_3_10_PLUS,
  21. PY_3_11_PLUS,
  22. PY_3_13_PLUS,
  23. _AnnotationExtractor,
  24. _get_annotations,
  25. get_generic_base,
  26. )
  27. from .exceptions import (
  28. DefaultAlreadySetError,
  29. FrozenInstanceError,
  30. NotAnAttrsClassError,
  31. UnannotatedAttributeError,
  32. )
  33. # This is used at least twice, so cache it here.
  34. _OBJ_SETATTR = object.__setattr__
  35. _INIT_FACTORY_PAT = "__attr_factory_%s"
  36. _CLASSVAR_PREFIXES = (
  37. "typing.ClassVar",
  38. "t.ClassVar",
  39. "ClassVar",
  40. "typing_extensions.ClassVar",
  41. )
  42. # we don't use a double-underscore prefix because that triggers
  43. # name mangling when trying to create a slot for the field
  44. # (when slots=True)
  45. _HASH_CACHE_FIELD = "_attrs_cached_hash"
  46. _EMPTY_METADATA_SINGLETON = types.MappingProxyType({})
  47. # Unique object for unequivocal getattr() defaults.
  48. _SENTINEL = object()
  49. _DEFAULT_ON_SETATTR = setters.pipe(setters.convert, setters.validate)
  50. class _Nothing(enum.Enum):
  51. """
  52. Sentinel to indicate the lack of a value when `None` is ambiguous.
  53. If extending attrs, you can use ``typing.Literal[NOTHING]`` to show
  54. that a value may be ``NOTHING``.
  55. .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False.
  56. .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant.
  57. """
  58. NOTHING = enum.auto()
  59. def __repr__(self):
  60. return "NOTHING"
  61. def __bool__(self):
  62. return False
  63. NOTHING = _Nothing.NOTHING
  64. """
  65. Sentinel to indicate the lack of a value when `None` is ambiguous.
  66. When using in 3rd party code, use `attrs.NothingType` for type annotations.
  67. """
  68. class _CacheHashWrapper(int):
  69. """
  70. An integer subclass that pickles / copies as None
  71. This is used for non-slots classes with ``cache_hash=True``, to avoid
  72. serializing a potentially (even likely) invalid hash value. Since `None`
  73. is the default value for uncalculated hashes, whenever this is copied,
  74. the copy's value for the hash should automatically reset.
  75. See GH #613 for more details.
  76. """
  77. def __reduce__(self, _none_constructor=type(None), _args=()): # noqa: B008
  78. return _none_constructor, _args
  79. def attrib(
  80. default=NOTHING,
  81. validator=None,
  82. repr=True,
  83. cmp=None,
  84. hash=None,
  85. init=True,
  86. metadata=None,
  87. type=None,
  88. converter=None,
  89. factory=None,
  90. kw_only=False,
  91. eq=None,
  92. order=None,
  93. on_setattr=None,
  94. alias=None,
  95. ):
  96. """
  97. Create a new field / attribute on a class.
  98. Identical to `attrs.field`, except it's not keyword-only.
  99. Consider using `attrs.field` in new code (``attr.ib`` will *never* go away,
  100. though).
  101. .. warning::
  102. Does **nothing** unless the class is also decorated with
  103. `attr.s` (or similar)!
  104. .. versionadded:: 15.2.0 *convert*
  105. .. versionadded:: 16.3.0 *metadata*
  106. .. versionchanged:: 17.1.0 *validator* can be a ``list`` now.
  107. .. versionchanged:: 17.1.0
  108. *hash* is `None` and therefore mirrors *eq* by default.
  109. .. versionadded:: 17.3.0 *type*
  110. .. deprecated:: 17.4.0 *convert*
  111. .. versionadded:: 17.4.0
  112. *converter* as a replacement for the deprecated *convert* to achieve
  113. consistency with other noun-based arguments.
  114. .. versionadded:: 18.1.0
  115. ``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``.
  116. .. versionadded:: 18.2.0 *kw_only*
  117. .. versionchanged:: 19.2.0 *convert* keyword argument removed.
  118. .. versionchanged:: 19.2.0 *repr* also accepts a custom callable.
  119. .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01.
  120. .. versionadded:: 19.2.0 *eq* and *order*
  121. .. versionadded:: 20.1.0 *on_setattr*
  122. .. versionchanged:: 20.3.0 *kw_only* backported to Python 2
  123. .. versionchanged:: 21.1.0
  124. *eq*, *order*, and *cmp* also accept a custom callable
  125. .. versionchanged:: 21.1.0 *cmp* undeprecated
  126. .. versionadded:: 22.2.0 *alias*
  127. """
  128. eq, eq_key, order, order_key = _determine_attrib_eq_order(
  129. cmp, eq, order, True
  130. )
  131. if hash is not None and hash is not True and hash is not False:
  132. msg = "Invalid value for hash. Must be True, False, or None."
  133. raise TypeError(msg)
  134. if factory is not None:
  135. if default is not NOTHING:
  136. msg = (
  137. "The `default` and `factory` arguments are mutually exclusive."
  138. )
  139. raise ValueError(msg)
  140. if not callable(factory):
  141. msg = "The `factory` argument must be a callable."
  142. raise ValueError(msg)
  143. default = Factory(factory)
  144. if metadata is None:
  145. metadata = {}
  146. # Apply syntactic sugar by auto-wrapping.
  147. if isinstance(on_setattr, (list, tuple)):
  148. on_setattr = setters.pipe(*on_setattr)
  149. if validator and isinstance(validator, (list, tuple)):
  150. validator = and_(*validator)
  151. if converter and isinstance(converter, (list, tuple)):
  152. converter = pipe(*converter)
  153. return _CountingAttr(
  154. default=default,
  155. validator=validator,
  156. repr=repr,
  157. cmp=None,
  158. hash=hash,
  159. init=init,
  160. converter=converter,
  161. metadata=metadata,
  162. type=type,
  163. kw_only=kw_only,
  164. eq=eq,
  165. eq_key=eq_key,
  166. order=order,
  167. order_key=order_key,
  168. on_setattr=on_setattr,
  169. alias=alias,
  170. )
  171. def _compile_and_eval(
  172. script: str,
  173. globs: dict[str, Any] | None,
  174. locs: Mapping[str, object] | None = None,
  175. filename: str = "",
  176. ) -> None:
  177. """
  178. Evaluate the script with the given global (globs) and local (locs)
  179. variables.
  180. """
  181. bytecode = compile(script, filename, "exec")
  182. eval(bytecode, globs, locs)
  183. def _linecache_and_compile(
  184. script: str,
  185. filename: str,
  186. globs: dict[str, Any] | None,
  187. locals: Mapping[str, object] | None = None,
  188. ) -> dict[str, Any]:
  189. """
  190. Cache the script with _linecache_, compile it and return the _locals_.
  191. """
  192. locs = {} if locals is None else locals
  193. # In order of debuggers like PDB being able to step through the code,
  194. # we add a fake linecache entry.
  195. count = 1
  196. base_filename = filename
  197. while True:
  198. linecache_tuple = (
  199. len(script),
  200. None,
  201. script.splitlines(True),
  202. filename,
  203. )
  204. old_val = linecache.cache.setdefault(filename, linecache_tuple)
  205. if old_val == linecache_tuple:
  206. break
  207. filename = f"{base_filename[:-1]}-{count}>"
  208. count += 1
  209. _compile_and_eval(script, globs, locs, filename)
  210. return locs
  211. def _make_attr_tuple_class(cls_name: str, attr_names: list[str]) -> type:
  212. """
  213. Create a tuple subclass to hold `Attribute`s for an `attrs` class.
  214. The subclass is a bare tuple with properties for names.
  215. class MyClassAttributes(tuple):
  216. __slots__ = ()
  217. x = property(itemgetter(0))
  218. """
  219. attr_class_name = f"{cls_name}Attributes"
  220. body = {}
  221. for i, attr_name in enumerate(attr_names):
  222. def getter(self, i=i):
  223. return self[i]
  224. body[attr_name] = property(getter)
  225. return type(attr_class_name, (tuple,), body)
  226. # Tuple class for extracted attributes from a class definition.
  227. # `base_attrs` is a subset of `attrs`.
  228. class _Attributes(NamedTuple):
  229. attrs: type
  230. base_attrs: list[Attribute]
  231. base_attrs_map: dict[str, type]
  232. def _is_class_var(annot):
  233. """
  234. Check whether *annot* is a typing.ClassVar.
  235. The string comparison hack is used to avoid evaluating all string
  236. annotations which would put attrs-based classes at a performance
  237. disadvantage compared to plain old classes.
  238. """
  239. annot = str(annot)
  240. # Annotation can be quoted.
  241. if annot.startswith(("'", '"')) and annot.endswith(("'", '"')):
  242. annot = annot[1:-1]
  243. return annot.startswith(_CLASSVAR_PREFIXES)
  244. def _has_own_attribute(cls, attrib_name):
  245. """
  246. Check whether *cls* defines *attrib_name* (and doesn't just inherit it).
  247. """
  248. return attrib_name in cls.__dict__
  249. def _collect_base_attrs(
  250. cls, taken_attr_names
  251. ) -> tuple[list[Attribute], dict[str, type]]:
  252. """
  253. Collect attr.ibs from base classes of *cls*, except *taken_attr_names*.
  254. """
  255. base_attrs = []
  256. base_attr_map = {} # A dictionary of base attrs to their classes.
  257. # Traverse the MRO and collect attributes.
  258. for base_cls in reversed(cls.__mro__[1:-1]):
  259. for a in getattr(base_cls, "__attrs_attrs__", []):
  260. if a.inherited or a.name in taken_attr_names:
  261. continue
  262. a = a.evolve(inherited=True) # noqa: PLW2901
  263. base_attrs.append(a)
  264. base_attr_map[a.name] = base_cls
  265. # For each name, only keep the freshest definition i.e. the furthest at the
  266. # back. base_attr_map is fine because it gets overwritten with every new
  267. # instance.
  268. filtered = []
  269. seen = set()
  270. for a in reversed(base_attrs):
  271. if a.name in seen:
  272. continue
  273. filtered.insert(0, a)
  274. seen.add(a.name)
  275. return filtered, base_attr_map
  276. def _collect_base_attrs_broken(cls, taken_attr_names):
  277. """
  278. Collect attr.ibs from base classes of *cls*, except *taken_attr_names*.
  279. N.B. *taken_attr_names* will be mutated.
  280. Adhere to the old incorrect behavior.
  281. Notably it collects from the front and considers inherited attributes which
  282. leads to the buggy behavior reported in #428.
  283. """
  284. base_attrs = []
  285. base_attr_map = {} # A dictionary of base attrs to their classes.
  286. # Traverse the MRO and collect attributes.
  287. for base_cls in cls.__mro__[1:-1]:
  288. for a in getattr(base_cls, "__attrs_attrs__", []):
  289. if a.name in taken_attr_names:
  290. continue
  291. a = a.evolve(inherited=True) # noqa: PLW2901
  292. taken_attr_names.add(a.name)
  293. base_attrs.append(a)
  294. base_attr_map[a.name] = base_cls
  295. return base_attrs, base_attr_map
  296. def _transform_attrs(
  297. cls, these, auto_attribs, kw_only, collect_by_mro, field_transformer
  298. ) -> _Attributes:
  299. """
  300. Transform all `_CountingAttr`s on a class into `Attribute`s.
  301. If *these* is passed, use that and don't look for them on the class.
  302. If *collect_by_mro* is True, collect them in the correct MRO order,
  303. otherwise use the old -- incorrect -- order. See #428.
  304. Return an `_Attributes`.
  305. """
  306. cd = cls.__dict__
  307. anns = _get_annotations(cls)
  308. if these is not None:
  309. ca_list = list(these.items())
  310. elif auto_attribs is True:
  311. ca_names = {
  312. name
  313. for name, attr in cd.items()
  314. if attr.__class__ is _CountingAttr
  315. }
  316. ca_list = []
  317. annot_names = set()
  318. for attr_name, type in anns.items():
  319. if _is_class_var(type):
  320. continue
  321. annot_names.add(attr_name)
  322. a = cd.get(attr_name, NOTHING)
  323. if a.__class__ is not _CountingAttr:
  324. a = attrib(a)
  325. ca_list.append((attr_name, a))
  326. unannotated = ca_names - annot_names
  327. if unannotated:
  328. raise UnannotatedAttributeError(
  329. "The following `attr.ib`s lack a type annotation: "
  330. + ", ".join(
  331. sorted(unannotated, key=lambda n: cd.get(n).counter)
  332. )
  333. + "."
  334. )
  335. else:
  336. ca_list = sorted(
  337. (
  338. (name, attr)
  339. for name, attr in cd.items()
  340. if attr.__class__ is _CountingAttr
  341. ),
  342. key=lambda e: e[1].counter,
  343. )
  344. fca = Attribute.from_counting_attr
  345. own_attrs = [
  346. fca(attr_name, ca, anns.get(attr_name)) for attr_name, ca in ca_list
  347. ]
  348. if collect_by_mro:
  349. base_attrs, base_attr_map = _collect_base_attrs(
  350. cls, {a.name for a in own_attrs}
  351. )
  352. else:
  353. base_attrs, base_attr_map = _collect_base_attrs_broken(
  354. cls, {a.name for a in own_attrs}
  355. )
  356. if kw_only:
  357. own_attrs = [a.evolve(kw_only=True) for a in own_attrs]
  358. base_attrs = [a.evolve(kw_only=True) for a in base_attrs]
  359. attrs = base_attrs + own_attrs
  360. if field_transformer is not None:
  361. attrs = tuple(field_transformer(cls, attrs))
  362. # Check attr order after executing the field_transformer.
  363. # Mandatory vs non-mandatory attr order only matters when they are part of
  364. # the __init__ signature and when they aren't kw_only (which are moved to
  365. # the end and can be mandatory or non-mandatory in any order, as they will
  366. # be specified as keyword args anyway). Check the order of those attrs:
  367. had_default = False
  368. for a in (a for a in attrs if a.init is not False and a.kw_only is False):
  369. if had_default is True and a.default is NOTHING:
  370. msg = f"No mandatory attributes allowed after an attribute with a default value or factory. Attribute in question: {a!r}"
  371. raise ValueError(msg)
  372. if had_default is False and a.default is not NOTHING:
  373. had_default = True
  374. # Resolve default field alias after executing field_transformer.
  375. # This allows field_transformer to differentiate between explicit vs
  376. # default aliases and supply their own defaults.
  377. for a in attrs:
  378. if not a.alias:
  379. # Evolve is very slow, so we hold our nose and do it dirty.
  380. _OBJ_SETATTR.__get__(a)("alias", _default_init_alias_for(a.name))
  381. # Create AttrsClass *after* applying the field_transformer since it may
  382. # add or remove attributes!
  383. attr_names = [a.name for a in attrs]
  384. AttrsClass = _make_attr_tuple_class(cls.__name__, attr_names)
  385. return _Attributes(AttrsClass(attrs), base_attrs, base_attr_map)
  386. def _make_cached_property_getattr(cached_properties, original_getattr, cls):
  387. lines = [
  388. # Wrapped to get `__class__` into closure cell for super()
  389. # (It will be replaced with the newly constructed class after construction).
  390. "def wrapper(_cls):",
  391. " __class__ = _cls",
  392. " def __getattr__(self, item, cached_properties=cached_properties, original_getattr=original_getattr, _cached_setattr_get=_cached_setattr_get):",
  393. " func = cached_properties.get(item)",
  394. " if func is not None:",
  395. " result = func(self)",
  396. " _setter = _cached_setattr_get(self)",
  397. " _setter(item, result)",
  398. " return result",
  399. ]
  400. if original_getattr is not None:
  401. lines.append(
  402. " return original_getattr(self, item)",
  403. )
  404. else:
  405. lines.extend(
  406. [
  407. " try:",
  408. " return super().__getattribute__(item)",
  409. " except AttributeError:",
  410. " if not hasattr(super(), '__getattr__'):",
  411. " raise",
  412. " return super().__getattr__(item)",
  413. " original_error = f\"'{self.__class__.__name__}' object has no attribute '{item}'\"",
  414. " raise AttributeError(original_error)",
  415. ]
  416. )
  417. lines.extend(
  418. [
  419. " return __getattr__",
  420. "__getattr__ = wrapper(_cls)",
  421. ]
  422. )
  423. unique_filename = _generate_unique_filename(cls, "getattr")
  424. glob = {
  425. "cached_properties": cached_properties,
  426. "_cached_setattr_get": _OBJ_SETATTR.__get__,
  427. "original_getattr": original_getattr,
  428. }
  429. return _linecache_and_compile(
  430. "\n".join(lines), unique_filename, glob, locals={"_cls": cls}
  431. )["__getattr__"]
  432. def _frozen_setattrs(self, name, value):
  433. """
  434. Attached to frozen classes as __setattr__.
  435. """
  436. if isinstance(self, BaseException) and name in (
  437. "__cause__",
  438. "__context__",
  439. "__traceback__",
  440. "__suppress_context__",
  441. "__notes__",
  442. ):
  443. BaseException.__setattr__(self, name, value)
  444. return
  445. raise FrozenInstanceError
  446. def _frozen_delattrs(self, name):
  447. """
  448. Attached to frozen classes as __delattr__.
  449. """
  450. if isinstance(self, BaseException) and name in ("__notes__",):
  451. BaseException.__delattr__(self, name)
  452. return
  453. raise FrozenInstanceError
  454. def evolve(*args, **changes):
  455. """
  456. Create a new instance, based on the first positional argument with
  457. *changes* applied.
  458. .. tip::
  459. On Python 3.13 and later, you can also use `copy.replace` instead.
  460. Args:
  461. inst:
  462. Instance of a class with *attrs* attributes. *inst* must be passed
  463. as a positional argument.
  464. changes:
  465. Keyword changes in the new copy.
  466. Returns:
  467. A copy of inst with *changes* incorporated.
  468. Raises:
  469. TypeError:
  470. If *attr_name* couldn't be found in the class ``__init__``.
  471. attrs.exceptions.NotAnAttrsClassError:
  472. If *cls* is not an *attrs* class.
  473. .. versionadded:: 17.1.0
  474. .. deprecated:: 23.1.0
  475. It is now deprecated to pass the instance using the keyword argument
  476. *inst*. It will raise a warning until at least April 2024, after which
  477. it will become an error. Always pass the instance as a positional
  478. argument.
  479. .. versionchanged:: 24.1.0
  480. *inst* can't be passed as a keyword argument anymore.
  481. """
  482. try:
  483. (inst,) = args
  484. except ValueError:
  485. msg = (
  486. f"evolve() takes 1 positional argument, but {len(args)} were given"
  487. )
  488. raise TypeError(msg) from None
  489. cls = inst.__class__
  490. attrs = fields(cls)
  491. for a in attrs:
  492. if not a.init:
  493. continue
  494. attr_name = a.name # To deal with private attributes.
  495. init_name = a.alias
  496. if init_name not in changes:
  497. changes[init_name] = getattr(inst, attr_name)
  498. return cls(**changes)
  499. class _ClassBuilder:
  500. """
  501. Iteratively build *one* class.
  502. """
  503. __slots__ = (
  504. "_add_method_dunders",
  505. "_attr_names",
  506. "_attrs",
  507. "_base_attr_map",
  508. "_base_names",
  509. "_cache_hash",
  510. "_cls",
  511. "_cls_dict",
  512. "_delete_attribs",
  513. "_frozen",
  514. "_has_custom_setattr",
  515. "_has_post_init",
  516. "_has_pre_init",
  517. "_is_exc",
  518. "_on_setattr",
  519. "_pre_init_has_args",
  520. "_repr_added",
  521. "_script_snippets",
  522. "_slots",
  523. "_weakref_slot",
  524. "_wrote_own_setattr",
  525. )
  526. def __init__(
  527. self,
  528. cls: type,
  529. these,
  530. slots,
  531. frozen,
  532. weakref_slot,
  533. getstate_setstate,
  534. auto_attribs,
  535. kw_only,
  536. cache_hash,
  537. is_exc,
  538. collect_by_mro,
  539. on_setattr,
  540. has_custom_setattr,
  541. field_transformer,
  542. ):
  543. attrs, base_attrs, base_map = _transform_attrs(
  544. cls,
  545. these,
  546. auto_attribs,
  547. kw_only,
  548. collect_by_mro,
  549. field_transformer,
  550. )
  551. self._cls = cls
  552. self._cls_dict = dict(cls.__dict__) if slots else {}
  553. self._attrs = attrs
  554. self._base_names = {a.name for a in base_attrs}
  555. self._base_attr_map = base_map
  556. self._attr_names = tuple(a.name for a in attrs)
  557. self._slots = slots
  558. self._frozen = frozen
  559. self._weakref_slot = weakref_slot
  560. self._cache_hash = cache_hash
  561. self._has_pre_init = bool(getattr(cls, "__attrs_pre_init__", False))
  562. self._pre_init_has_args = False
  563. if self._has_pre_init:
  564. # Check if the pre init method has more arguments than just `self`
  565. # We want to pass arguments if pre init expects arguments
  566. pre_init_func = cls.__attrs_pre_init__
  567. pre_init_signature = inspect.signature(pre_init_func)
  568. self._pre_init_has_args = len(pre_init_signature.parameters) > 1
  569. self._has_post_init = bool(getattr(cls, "__attrs_post_init__", False))
  570. self._delete_attribs = not bool(these)
  571. self._is_exc = is_exc
  572. self._on_setattr = on_setattr
  573. self._has_custom_setattr = has_custom_setattr
  574. self._wrote_own_setattr = False
  575. self._cls_dict["__attrs_attrs__"] = self._attrs
  576. if frozen:
  577. self._cls_dict["__setattr__"] = _frozen_setattrs
  578. self._cls_dict["__delattr__"] = _frozen_delattrs
  579. self._wrote_own_setattr = True
  580. elif on_setattr in (
  581. _DEFAULT_ON_SETATTR,
  582. setters.validate,
  583. setters.convert,
  584. ):
  585. has_validator = has_converter = False
  586. for a in attrs:
  587. if a.validator is not None:
  588. has_validator = True
  589. if a.converter is not None:
  590. has_converter = True
  591. if has_validator and has_converter:
  592. break
  593. if (
  594. (
  595. on_setattr == _DEFAULT_ON_SETATTR
  596. and not (has_validator or has_converter)
  597. )
  598. or (on_setattr == setters.validate and not has_validator)
  599. or (on_setattr == setters.convert and not has_converter)
  600. ):
  601. # If class-level on_setattr is set to convert + validate, but
  602. # there's no field to convert or validate, pretend like there's
  603. # no on_setattr.
  604. self._on_setattr = None
  605. if getstate_setstate:
  606. (
  607. self._cls_dict["__getstate__"],
  608. self._cls_dict["__setstate__"],
  609. ) = self._make_getstate_setstate()
  610. # tuples of script, globs, hook
  611. self._script_snippets: list[
  612. tuple[str, dict, Callable[[dict, dict], Any]]
  613. ] = []
  614. self._repr_added = False
  615. # We want to only do this check once; in 99.9% of cases these
  616. # exist.
  617. if not hasattr(self._cls, "__module__") or not hasattr(
  618. self._cls, "__qualname__"
  619. ):
  620. self._add_method_dunders = self._add_method_dunders_safe
  621. else:
  622. self._add_method_dunders = self._add_method_dunders_unsafe
  623. def __repr__(self):
  624. return f"<_ClassBuilder(cls={self._cls.__name__})>"
  625. def _eval_snippets(self) -> None:
  626. """
  627. Evaluate any registered snippets in one go.
  628. """
  629. script = "\n".join([snippet[0] for snippet in self._script_snippets])
  630. globs = {}
  631. for _, snippet_globs, _ in self._script_snippets:
  632. globs.update(snippet_globs)
  633. locs = _linecache_and_compile(
  634. script,
  635. _generate_unique_filename(self._cls, "methods"),
  636. globs,
  637. )
  638. for _, _, hook in self._script_snippets:
  639. hook(self._cls_dict, locs)
  640. def build_class(self):
  641. """
  642. Finalize class based on the accumulated configuration.
  643. Builder cannot be used after calling this method.
  644. """
  645. self._eval_snippets()
  646. if self._slots is True:
  647. cls = self._create_slots_class()
  648. else:
  649. cls = self._patch_original_class()
  650. if PY_3_10_PLUS:
  651. cls = abc.update_abstractmethods(cls)
  652. # The method gets only called if it's not inherited from a base class.
  653. # _has_own_attribute does NOT work properly for classmethods.
  654. if (
  655. getattr(cls, "__attrs_init_subclass__", None)
  656. and "__attrs_init_subclass__" not in cls.__dict__
  657. ):
  658. cls.__attrs_init_subclass__()
  659. return cls
  660. def _patch_original_class(self):
  661. """
  662. Apply accumulated methods and return the class.
  663. """
  664. cls = self._cls
  665. base_names = self._base_names
  666. # Clean class of attribute definitions (`attr.ib()`s).
  667. if self._delete_attribs:
  668. for name in self._attr_names:
  669. if (
  670. name not in base_names
  671. and getattr(cls, name, _SENTINEL) is not _SENTINEL
  672. ):
  673. # An AttributeError can happen if a base class defines a
  674. # class variable and we want to set an attribute with the
  675. # same name by using only a type annotation.
  676. with contextlib.suppress(AttributeError):
  677. delattr(cls, name)
  678. # Attach our dunder methods.
  679. for name, value in self._cls_dict.items():
  680. setattr(cls, name, value)
  681. # If we've inherited an attrs __setattr__ and don't write our own,
  682. # reset it to object's.
  683. if not self._wrote_own_setattr and getattr(
  684. cls, "__attrs_own_setattr__", False
  685. ):
  686. cls.__attrs_own_setattr__ = False
  687. if not self._has_custom_setattr:
  688. cls.__setattr__ = _OBJ_SETATTR
  689. return cls
  690. def _create_slots_class(self):
  691. """
  692. Build and return a new class with a `__slots__` attribute.
  693. """
  694. cd = {
  695. k: v
  696. for k, v in self._cls_dict.items()
  697. if k not in (*tuple(self._attr_names), "__dict__", "__weakref__")
  698. }
  699. # If our class doesn't have its own implementation of __setattr__
  700. # (either from the user or by us), check the bases, if one of them has
  701. # an attrs-made __setattr__, that needs to be reset. We don't walk the
  702. # MRO because we only care about our immediate base classes.
  703. # XXX: This can be confused by subclassing a slotted attrs class with
  704. # XXX: a non-attrs class and subclass the resulting class with an attrs
  705. # XXX: class. See `test_slotted_confused` for details. For now that's
  706. # XXX: OK with us.
  707. if not self._wrote_own_setattr:
  708. cd["__attrs_own_setattr__"] = False
  709. if not self._has_custom_setattr:
  710. for base_cls in self._cls.__bases__:
  711. if base_cls.__dict__.get("__attrs_own_setattr__", False):
  712. cd["__setattr__"] = _OBJ_SETATTR
  713. break
  714. # Traverse the MRO to collect existing slots
  715. # and check for an existing __weakref__.
  716. existing_slots = {}
  717. weakref_inherited = False
  718. for base_cls in self._cls.__mro__[1:-1]:
  719. if base_cls.__dict__.get("__weakref__", None) is not None:
  720. weakref_inherited = True
  721. existing_slots.update(
  722. {
  723. name: getattr(base_cls, name)
  724. for name in getattr(base_cls, "__slots__", [])
  725. }
  726. )
  727. base_names = set(self._base_names)
  728. names = self._attr_names
  729. if (
  730. self._weakref_slot
  731. and "__weakref__" not in getattr(self._cls, "__slots__", ())
  732. and "__weakref__" not in names
  733. and not weakref_inherited
  734. ):
  735. names += ("__weakref__",)
  736. cached_properties = {
  737. name: cached_prop.func
  738. for name, cached_prop in cd.items()
  739. if isinstance(cached_prop, cached_property)
  740. }
  741. # Collect methods with a `__class__` reference that are shadowed in the new class.
  742. # To know to update them.
  743. additional_closure_functions_to_update = []
  744. if cached_properties:
  745. class_annotations = _get_annotations(self._cls)
  746. for name, func in cached_properties.items():
  747. # Add cached properties to names for slotting.
  748. names += (name,)
  749. # Clear out function from class to avoid clashing.
  750. del cd[name]
  751. additional_closure_functions_to_update.append(func)
  752. annotation = inspect.signature(func).return_annotation
  753. if annotation is not inspect.Parameter.empty:
  754. class_annotations[name] = annotation
  755. original_getattr = cd.get("__getattr__")
  756. if original_getattr is not None:
  757. additional_closure_functions_to_update.append(original_getattr)
  758. cd["__getattr__"] = _make_cached_property_getattr(
  759. cached_properties, original_getattr, self._cls
  760. )
  761. # We only add the names of attributes that aren't inherited.
  762. # Setting __slots__ to inherited attributes wastes memory.
  763. slot_names = [name for name in names if name not in base_names]
  764. # There are slots for attributes from current class
  765. # that are defined in parent classes.
  766. # As their descriptors may be overridden by a child class,
  767. # we collect them here and update the class dict
  768. reused_slots = {
  769. slot: slot_descriptor
  770. for slot, slot_descriptor in existing_slots.items()
  771. if slot in slot_names
  772. }
  773. slot_names = [name for name in slot_names if name not in reused_slots]
  774. cd.update(reused_slots)
  775. if self._cache_hash:
  776. slot_names.append(_HASH_CACHE_FIELD)
  777. cd["__slots__"] = tuple(slot_names)
  778. cd["__qualname__"] = self._cls.__qualname__
  779. # Create new class based on old class and our methods.
  780. cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)
  781. # The following is a fix for
  782. # <https://github.com/python-attrs/attrs/issues/102>.
  783. # If a method mentions `__class__` or uses the no-arg super(), the
  784. # compiler will bake a reference to the class in the method itself
  785. # as `method.__closure__`. Since we replace the class with a
  786. # clone, we rewrite these references so it keeps working.
  787. for item in itertools.chain(
  788. cls.__dict__.values(), additional_closure_functions_to_update
  789. ):
  790. if isinstance(item, (classmethod, staticmethod)):
  791. # Class- and staticmethods hide their functions inside.
  792. # These might need to be rewritten as well.
  793. closure_cells = getattr(item.__func__, "__closure__", None)
  794. elif isinstance(item, property):
  795. # Workaround for property `super()` shortcut (PY3-only).
  796. # There is no universal way for other descriptors.
  797. closure_cells = getattr(item.fget, "__closure__", None)
  798. else:
  799. closure_cells = getattr(item, "__closure__", None)
  800. if not closure_cells: # Catch None or the empty list.
  801. continue
  802. for cell in closure_cells:
  803. try:
  804. match = cell.cell_contents is self._cls
  805. except ValueError: # noqa: PERF203
  806. # ValueError: Cell is empty
  807. pass
  808. else:
  809. if match:
  810. cell.cell_contents = cls
  811. return cls
  812. def add_repr(self, ns):
  813. script, globs = _make_repr_script(self._attrs, ns)
  814. def _attach_repr(cls_dict, globs):
  815. cls_dict["__repr__"] = self._add_method_dunders(globs["__repr__"])
  816. self._script_snippets.append((script, globs, _attach_repr))
  817. self._repr_added = True
  818. return self
  819. def add_str(self):
  820. if not self._repr_added:
  821. msg = "__str__ can only be generated if a __repr__ exists."
  822. raise ValueError(msg)
  823. def __str__(self):
  824. return self.__repr__()
  825. self._cls_dict["__str__"] = self._add_method_dunders(__str__)
  826. return self
  827. def _make_getstate_setstate(self):
  828. """
  829. Create custom __setstate__ and __getstate__ methods.
  830. """
  831. # __weakref__ is not writable.
  832. state_attr_names = tuple(
  833. an for an in self._attr_names if an != "__weakref__"
  834. )
  835. def slots_getstate(self):
  836. """
  837. Automatically created by attrs.
  838. """
  839. return {name: getattr(self, name) for name in state_attr_names}
  840. hash_caching_enabled = self._cache_hash
  841. def slots_setstate(self, state):
  842. """
  843. Automatically created by attrs.
  844. """
  845. __bound_setattr = _OBJ_SETATTR.__get__(self)
  846. if isinstance(state, tuple):
  847. # Backward compatibility with attrs instances pickled with
  848. # attrs versions before v22.2.0 which stored tuples.
  849. for name, value in zip(state_attr_names, state):
  850. __bound_setattr(name, value)
  851. else:
  852. for name in state_attr_names:
  853. if name in state:
  854. __bound_setattr(name, state[name])
  855. # The hash code cache is not included when the object is
  856. # serialized, but it still needs to be initialized to None to
  857. # indicate that the first call to __hash__ should be a cache
  858. # miss.
  859. if hash_caching_enabled:
  860. __bound_setattr(_HASH_CACHE_FIELD, None)
  861. return slots_getstate, slots_setstate
  862. def make_unhashable(self):
  863. self._cls_dict["__hash__"] = None
  864. return self
  865. def add_hash(self):
  866. script, globs = _make_hash_script(
  867. self._cls,
  868. self._attrs,
  869. frozen=self._frozen,
  870. cache_hash=self._cache_hash,
  871. )
  872. def attach_hash(cls_dict: dict, locs: dict) -> None:
  873. cls_dict["__hash__"] = self._add_method_dunders(locs["__hash__"])
  874. self._script_snippets.append((script, globs, attach_hash))
  875. return self
  876. def add_init(self):
  877. script, globs, annotations = _make_init_script(
  878. self._cls,
  879. self._attrs,
  880. self._has_pre_init,
  881. self._pre_init_has_args,
  882. self._has_post_init,
  883. self._frozen,
  884. self._slots,
  885. self._cache_hash,
  886. self._base_attr_map,
  887. self._is_exc,
  888. self._on_setattr,
  889. attrs_init=False,
  890. )
  891. def _attach_init(cls_dict, globs):
  892. init = globs["__init__"]
  893. init.__annotations__ = annotations
  894. cls_dict["__init__"] = self._add_method_dunders(init)
  895. self._script_snippets.append((script, globs, _attach_init))
  896. return self
  897. def add_replace(self):
  898. self._cls_dict["__replace__"] = self._add_method_dunders(
  899. lambda self, **changes: evolve(self, **changes)
  900. )
  901. return self
  902. def add_match_args(self):
  903. self._cls_dict["__match_args__"] = tuple(
  904. field.name
  905. for field in self._attrs
  906. if field.init and not field.kw_only
  907. )
  908. def add_attrs_init(self):
  909. script, globs, annotations = _make_init_script(
  910. self._cls,
  911. self._attrs,
  912. self._has_pre_init,
  913. self._pre_init_has_args,
  914. self._has_post_init,
  915. self._frozen,
  916. self._slots,
  917. self._cache_hash,
  918. self._base_attr_map,
  919. self._is_exc,
  920. self._on_setattr,
  921. attrs_init=True,
  922. )
  923. def _attach_attrs_init(cls_dict, globs):
  924. init = globs["__attrs_init__"]
  925. init.__annotations__ = annotations
  926. cls_dict["__attrs_init__"] = self._add_method_dunders(init)
  927. self._script_snippets.append((script, globs, _attach_attrs_init))
  928. return self
  929. def add_eq(self):
  930. cd = self._cls_dict
  931. script, globs = _make_eq_script(self._attrs)
  932. def _attach_eq(cls_dict, globs):
  933. cls_dict["__eq__"] = self._add_method_dunders(globs["__eq__"])
  934. self._script_snippets.append((script, globs, _attach_eq))
  935. cd["__ne__"] = __ne__
  936. return self
  937. def add_order(self):
  938. cd = self._cls_dict
  939. cd["__lt__"], cd["__le__"], cd["__gt__"], cd["__ge__"] = (
  940. self._add_method_dunders(meth)
  941. for meth in _make_order(self._cls, self._attrs)
  942. )
  943. return self
  944. def add_setattr(self):
  945. sa_attrs = {}
  946. for a in self._attrs:
  947. on_setattr = a.on_setattr or self._on_setattr
  948. if on_setattr and on_setattr is not setters.NO_OP:
  949. sa_attrs[a.name] = a, on_setattr
  950. if not sa_attrs:
  951. return self
  952. if self._has_custom_setattr:
  953. # We need to write a __setattr__ but there already is one!
  954. msg = "Can't combine custom __setattr__ with on_setattr hooks."
  955. raise ValueError(msg)
  956. # docstring comes from _add_method_dunders
  957. def __setattr__(self, name, val):
  958. try:
  959. a, hook = sa_attrs[name]
  960. except KeyError:
  961. nval = val
  962. else:
  963. nval = hook(self, a, val)
  964. _OBJ_SETATTR(self, name, nval)
  965. self._cls_dict["__attrs_own_setattr__"] = True
  966. self._cls_dict["__setattr__"] = self._add_method_dunders(__setattr__)
  967. self._wrote_own_setattr = True
  968. return self
  969. def _add_method_dunders_unsafe(self, method: Callable) -> Callable:
  970. """
  971. Add __module__ and __qualname__ to a *method*.
  972. """
  973. method.__module__ = self._cls.__module__
  974. method.__qualname__ = f"{self._cls.__qualname__}.{method.__name__}"
  975. method.__doc__ = (
  976. f"Method generated by attrs for class {self._cls.__qualname__}."
  977. )
  978. return method
  979. def _add_method_dunders_safe(self, method: Callable) -> Callable:
  980. """
  981. Add __module__ and __qualname__ to a *method* if possible.
  982. """
  983. with contextlib.suppress(AttributeError):
  984. method.__module__ = self._cls.__module__
  985. with contextlib.suppress(AttributeError):
  986. method.__qualname__ = f"{self._cls.__qualname__}.{method.__name__}"
  987. with contextlib.suppress(AttributeError):
  988. method.__doc__ = f"Method generated by attrs for class {self._cls.__qualname__}."
  989. return method
  990. def _determine_attrs_eq_order(cmp, eq, order, default_eq):
  991. """
  992. Validate the combination of *cmp*, *eq*, and *order*. Derive the effective
  993. values of eq and order. If *eq* is None, set it to *default_eq*.
  994. """
  995. if cmp is not None and any((eq is not None, order is not None)):
  996. msg = "Don't mix `cmp` with `eq' and `order`."
  997. raise ValueError(msg)
  998. # cmp takes precedence due to bw-compatibility.
  999. if cmp is not None:
  1000. return cmp, cmp
  1001. # If left None, equality is set to the specified default and ordering
  1002. # mirrors equality.
  1003. if eq is None:
  1004. eq = default_eq
  1005. if order is None:
  1006. order = eq
  1007. if eq is False and order is True:
  1008. msg = "`order` can only be True if `eq` is True too."
  1009. raise ValueError(msg)
  1010. return eq, order
  1011. def _determine_attrib_eq_order(cmp, eq, order, default_eq):
  1012. """
  1013. Validate the combination of *cmp*, *eq*, and *order*. Derive the effective
  1014. values of eq and order. If *eq* is None, set it to *default_eq*.
  1015. """
  1016. if cmp is not None and any((eq is not None, order is not None)):
  1017. msg = "Don't mix `cmp` with `eq' and `order`."
  1018. raise ValueError(msg)
  1019. def decide_callable_or_boolean(value):
  1020. """
  1021. Decide whether a key function is used.
  1022. """
  1023. if callable(value):
  1024. value, key = True, value
  1025. else:
  1026. key = None
  1027. return value, key
  1028. # cmp takes precedence due to bw-compatibility.
  1029. if cmp is not None:
  1030. cmp, cmp_key = decide_callable_or_boolean(cmp)
  1031. return cmp, cmp_key, cmp, cmp_key
  1032. # If left None, equality is set to the specified default and ordering
  1033. # mirrors equality.
  1034. if eq is None:
  1035. eq, eq_key = default_eq, None
  1036. else:
  1037. eq, eq_key = decide_callable_or_boolean(eq)
  1038. if order is None:
  1039. order, order_key = eq, eq_key
  1040. else:
  1041. order, order_key = decide_callable_or_boolean(order)
  1042. if eq is False and order is True:
  1043. msg = "`order` can only be True if `eq` is True too."
  1044. raise ValueError(msg)
  1045. return eq, eq_key, order, order_key
  1046. def _determine_whether_to_implement(
  1047. cls, flag, auto_detect, dunders, default=True
  1048. ):
  1049. """
  1050. Check whether we should implement a set of methods for *cls*.
  1051. *flag* is the argument passed into @attr.s like 'init', *auto_detect* the
  1052. same as passed into @attr.s and *dunders* is a tuple of attribute names
  1053. whose presence signal that the user has implemented it themselves.
  1054. Return *default* if no reason for either for or against is found.
  1055. """
  1056. if flag is True or flag is False:
  1057. return flag
  1058. if flag is None and auto_detect is False:
  1059. return default
  1060. # Logically, flag is None and auto_detect is True here.
  1061. for dunder in dunders:
  1062. if _has_own_attribute(cls, dunder):
  1063. return False
  1064. return default
  1065. def attrs(
  1066. maybe_cls=None,
  1067. these=None,
  1068. repr_ns=None,
  1069. repr=None,
  1070. cmp=None,
  1071. hash=None,
  1072. init=None,
  1073. slots=False,
  1074. frozen=False,
  1075. weakref_slot=True,
  1076. str=False,
  1077. auto_attribs=False,
  1078. kw_only=False,
  1079. cache_hash=False,
  1080. auto_exc=False,
  1081. eq=None,
  1082. order=None,
  1083. auto_detect=False,
  1084. collect_by_mro=False,
  1085. getstate_setstate=None,
  1086. on_setattr=None,
  1087. field_transformer=None,
  1088. match_args=True,
  1089. unsafe_hash=None,
  1090. ):
  1091. r"""
  1092. A class decorator that adds :term:`dunder methods` according to the
  1093. specified attributes using `attr.ib` or the *these* argument.
  1094. Consider using `attrs.define` / `attrs.frozen` in new code (``attr.s`` will
  1095. *never* go away, though).
  1096. Args:
  1097. repr_ns (str):
  1098. When using nested classes, there was no way in Python 2 to
  1099. automatically detect that. This argument allows to set a custom
  1100. name for a more meaningful ``repr`` output. This argument is
  1101. pointless in Python 3 and is therefore deprecated.
  1102. .. caution::
  1103. Refer to `attrs.define` for the rest of the parameters, but note that they
  1104. can have different defaults.
  1105. Notably, leaving *on_setattr* as `None` will **not** add any hooks.
  1106. .. versionadded:: 16.0.0 *slots*
  1107. .. versionadded:: 16.1.0 *frozen*
  1108. .. versionadded:: 16.3.0 *str*
  1109. .. versionadded:: 16.3.0 Support for ``__attrs_post_init__``.
  1110. .. versionchanged:: 17.1.0
  1111. *hash* supports `None` as value which is also the default now.
  1112. .. versionadded:: 17.3.0 *auto_attribs*
  1113. .. versionchanged:: 18.1.0
  1114. If *these* is passed, no attributes are deleted from the class body.
  1115. .. versionchanged:: 18.1.0 If *these* is ordered, the order is retained.
  1116. .. versionadded:: 18.2.0 *weakref_slot*
  1117. .. deprecated:: 18.2.0
  1118. ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now raise a
  1119. `DeprecationWarning` if the classes compared are subclasses of
  1120. each other. ``__eq`` and ``__ne__`` never tried to compared subclasses
  1121. to each other.
  1122. .. versionchanged:: 19.2.0
  1123. ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now do not consider
  1124. subclasses comparable anymore.
  1125. .. versionadded:: 18.2.0 *kw_only*
  1126. .. versionadded:: 18.2.0 *cache_hash*
  1127. .. versionadded:: 19.1.0 *auto_exc*
  1128. .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01.
  1129. .. versionadded:: 19.2.0 *eq* and *order*
  1130. .. versionadded:: 20.1.0 *auto_detect*
  1131. .. versionadded:: 20.1.0 *collect_by_mro*
  1132. .. versionadded:: 20.1.0 *getstate_setstate*
  1133. .. versionadded:: 20.1.0 *on_setattr*
  1134. .. versionadded:: 20.3.0 *field_transformer*
  1135. .. versionchanged:: 21.1.0
  1136. ``init=False`` injects ``__attrs_init__``
  1137. .. versionchanged:: 21.1.0 Support for ``__attrs_pre_init__``
  1138. .. versionchanged:: 21.1.0 *cmp* undeprecated
  1139. .. versionadded:: 21.3.0 *match_args*
  1140. .. versionadded:: 22.2.0
  1141. *unsafe_hash* as an alias for *hash* (for :pep:`681` compliance).
  1142. .. deprecated:: 24.1.0 *repr_ns*
  1143. .. versionchanged:: 24.1.0
  1144. Instances are not compared as tuples of attributes anymore, but using a
  1145. big ``and`` condition. This is faster and has more correct behavior for
  1146. uncomparable values like `math.nan`.
  1147. .. versionadded:: 24.1.0
  1148. If a class has an *inherited* classmethod called
  1149. ``__attrs_init_subclass__``, it is executed after the class is created.
  1150. .. deprecated:: 24.1.0 *hash* is deprecated in favor of *unsafe_hash*.
  1151. """
  1152. if repr_ns is not None:
  1153. import warnings
  1154. warnings.warn(
  1155. DeprecationWarning(
  1156. "The `repr_ns` argument is deprecated and will be removed in or after August 2025."
  1157. ),
  1158. stacklevel=2,
  1159. )
  1160. eq_, order_ = _determine_attrs_eq_order(cmp, eq, order, None)
  1161. # unsafe_hash takes precedence due to PEP 681.
  1162. if unsafe_hash is not None:
  1163. hash = unsafe_hash
  1164. if isinstance(on_setattr, (list, tuple)):
  1165. on_setattr = setters.pipe(*on_setattr)
  1166. def wrap(cls):
  1167. is_frozen = frozen or _has_frozen_base_class(cls)
  1168. is_exc = auto_exc is True and issubclass(cls, BaseException)
  1169. has_own_setattr = auto_detect and _has_own_attribute(
  1170. cls, "__setattr__"
  1171. )
  1172. if has_own_setattr and is_frozen:
  1173. msg = "Can't freeze a class with a custom __setattr__."
  1174. raise ValueError(msg)
  1175. builder = _ClassBuilder(
  1176. cls,
  1177. these,
  1178. slots,
  1179. is_frozen,
  1180. weakref_slot,
  1181. _determine_whether_to_implement(
  1182. cls,
  1183. getstate_setstate,
  1184. auto_detect,
  1185. ("__getstate__", "__setstate__"),
  1186. default=slots,
  1187. ),
  1188. auto_attribs,
  1189. kw_only,
  1190. cache_hash,
  1191. is_exc,
  1192. collect_by_mro,
  1193. on_setattr,
  1194. has_own_setattr,
  1195. field_transformer,
  1196. )
  1197. if _determine_whether_to_implement(
  1198. cls, repr, auto_detect, ("__repr__",)
  1199. ):
  1200. builder.add_repr(repr_ns)
  1201. if str is True:
  1202. builder.add_str()
  1203. eq = _determine_whether_to_implement(
  1204. cls, eq_, auto_detect, ("__eq__", "__ne__")
  1205. )
  1206. if not is_exc and eq is True:
  1207. builder.add_eq()
  1208. if not is_exc and _determine_whether_to_implement(
  1209. cls, order_, auto_detect, ("__lt__", "__le__", "__gt__", "__ge__")
  1210. ):
  1211. builder.add_order()
  1212. if not frozen:
  1213. builder.add_setattr()
  1214. nonlocal hash
  1215. if (
  1216. hash is None
  1217. and auto_detect is True
  1218. and _has_own_attribute(cls, "__hash__")
  1219. ):
  1220. hash = False
  1221. if hash is not True and hash is not False and hash is not None:
  1222. # Can't use `hash in` because 1 == True for example.
  1223. msg = "Invalid value for hash. Must be True, False, or None."
  1224. raise TypeError(msg)
  1225. if hash is False or (hash is None and eq is False) or is_exc:
  1226. # Don't do anything. Should fall back to __object__'s __hash__
  1227. # which is by id.
  1228. if cache_hash:
  1229. msg = "Invalid value for cache_hash. To use hash caching, hashing must be either explicitly or implicitly enabled."
  1230. raise TypeError(msg)
  1231. elif hash is True or (
  1232. hash is None and eq is True and is_frozen is True
  1233. ):
  1234. # Build a __hash__ if told so, or if it's safe.
  1235. builder.add_hash()
  1236. else:
  1237. # Raise TypeError on attempts to hash.
  1238. if cache_hash:
  1239. msg = "Invalid value for cache_hash. To use hash caching, hashing must be either explicitly or implicitly enabled."
  1240. raise TypeError(msg)
  1241. builder.make_unhashable()
  1242. if _determine_whether_to_implement(
  1243. cls, init, auto_detect, ("__init__",)
  1244. ):
  1245. builder.add_init()
  1246. else:
  1247. builder.add_attrs_init()
  1248. if cache_hash:
  1249. msg = "Invalid value for cache_hash. To use hash caching, init must be True."
  1250. raise TypeError(msg)
  1251. if PY_3_13_PLUS and not _has_own_attribute(cls, "__replace__"):
  1252. builder.add_replace()
  1253. if (
  1254. PY_3_10_PLUS
  1255. and match_args
  1256. and not _has_own_attribute(cls, "__match_args__")
  1257. ):
  1258. builder.add_match_args()
  1259. return builder.build_class()
  1260. # maybe_cls's type depends on the usage of the decorator. It's a class
  1261. # if it's used as `@attrs` but `None` if used as `@attrs()`.
  1262. if maybe_cls is None:
  1263. return wrap
  1264. return wrap(maybe_cls)
  1265. _attrs = attrs
  1266. """
  1267. Internal alias so we can use it in functions that take an argument called
  1268. *attrs*.
  1269. """
  1270. def _has_frozen_base_class(cls):
  1271. """
  1272. Check whether *cls* has a frozen ancestor by looking at its
  1273. __setattr__.
  1274. """
  1275. return cls.__setattr__ is _frozen_setattrs
  1276. def _generate_unique_filename(cls: type, func_name: str) -> str:
  1277. """
  1278. Create a "filename" suitable for a function being generated.
  1279. """
  1280. return (
  1281. f"<attrs generated {func_name} {cls.__module__}."
  1282. f"{getattr(cls, '__qualname__', cls.__name__)}>"
  1283. )
  1284. def _make_hash_script(
  1285. cls: type, attrs: list[Attribute], frozen: bool, cache_hash: bool
  1286. ) -> tuple[str, dict]:
  1287. attrs = tuple(
  1288. a for a in attrs if a.hash is True or (a.hash is None and a.eq is True)
  1289. )
  1290. tab = " "
  1291. type_hash = hash(_generate_unique_filename(cls, "hash"))
  1292. # If eq is custom generated, we need to include the functions in globs
  1293. globs = {}
  1294. hash_def = "def __hash__(self"
  1295. hash_func = "hash(("
  1296. closing_braces = "))"
  1297. if not cache_hash:
  1298. hash_def += "):"
  1299. else:
  1300. hash_def += ", *"
  1301. hash_def += ", _cache_wrapper=__import__('attr._make')._make._CacheHashWrapper):"
  1302. hash_func = "_cache_wrapper(" + hash_func
  1303. closing_braces += ")"
  1304. method_lines = [hash_def]
  1305. def append_hash_computation_lines(prefix, indent):
  1306. """
  1307. Generate the code for actually computing the hash code.
  1308. Below this will either be returned directly or used to compute
  1309. a value which is then cached, depending on the value of cache_hash
  1310. """
  1311. method_lines.extend(
  1312. [
  1313. indent + prefix + hash_func,
  1314. indent + f" {type_hash},",
  1315. ]
  1316. )
  1317. for a in attrs:
  1318. if a.eq_key:
  1319. cmp_name = f"_{a.name}_key"
  1320. globs[cmp_name] = a.eq_key
  1321. method_lines.append(
  1322. indent + f" {cmp_name}(self.{a.name}),"
  1323. )
  1324. else:
  1325. method_lines.append(indent + f" self.{a.name},")
  1326. method_lines.append(indent + " " + closing_braces)
  1327. if cache_hash:
  1328. method_lines.append(tab + f"if self.{_HASH_CACHE_FIELD} is None:")
  1329. if frozen:
  1330. append_hash_computation_lines(
  1331. f"object.__setattr__(self, '{_HASH_CACHE_FIELD}', ", tab * 2
  1332. )
  1333. method_lines.append(tab * 2 + ")") # close __setattr__
  1334. else:
  1335. append_hash_computation_lines(
  1336. f"self.{_HASH_CACHE_FIELD} = ", tab * 2
  1337. )
  1338. method_lines.append(tab + f"return self.{_HASH_CACHE_FIELD}")
  1339. else:
  1340. append_hash_computation_lines("return ", tab)
  1341. script = "\n".join(method_lines)
  1342. return script, globs
  1343. def _add_hash(cls: type, attrs: list[Attribute]):
  1344. """
  1345. Add a hash method to *cls*.
  1346. """
  1347. script, globs = _make_hash_script(
  1348. cls, attrs, frozen=False, cache_hash=False
  1349. )
  1350. _compile_and_eval(
  1351. script, globs, filename=_generate_unique_filename(cls, "__hash__")
  1352. )
  1353. cls.__hash__ = globs["__hash__"]
  1354. return cls
  1355. def __ne__(self, other):
  1356. """
  1357. Check equality and either forward a NotImplemented or
  1358. return the result negated.
  1359. """
  1360. result = self.__eq__(other)
  1361. if result is NotImplemented:
  1362. return NotImplemented
  1363. return not result
  1364. def _make_eq_script(attrs: list) -> tuple[str, dict]:
  1365. """
  1366. Create __eq__ method for *cls* with *attrs*.
  1367. """
  1368. attrs = [a for a in attrs if a.eq]
  1369. lines = [
  1370. "def __eq__(self, other):",
  1371. " if other.__class__ is not self.__class__:",
  1372. " return NotImplemented",
  1373. ]
  1374. globs = {}
  1375. if attrs:
  1376. lines.append(" return (")
  1377. for a in attrs:
  1378. if a.eq_key:
  1379. cmp_name = f"_{a.name}_key"
  1380. # Add the key function to the global namespace
  1381. # of the evaluated function.
  1382. globs[cmp_name] = a.eq_key
  1383. lines.append(
  1384. f" {cmp_name}(self.{a.name}) == {cmp_name}(other.{a.name})"
  1385. )
  1386. else:
  1387. lines.append(f" self.{a.name} == other.{a.name}")
  1388. if a is not attrs[-1]:
  1389. lines[-1] = f"{lines[-1]} and"
  1390. lines.append(" )")
  1391. else:
  1392. lines.append(" return True")
  1393. script = "\n".join(lines)
  1394. return script, globs
  1395. def _make_order(cls, attrs):
  1396. """
  1397. Create ordering methods for *cls* with *attrs*.
  1398. """
  1399. attrs = [a for a in attrs if a.order]
  1400. def attrs_to_tuple(obj):
  1401. """
  1402. Save us some typing.
  1403. """
  1404. return tuple(
  1405. key(value) if key else value
  1406. for value, key in (
  1407. (getattr(obj, a.name), a.order_key) for a in attrs
  1408. )
  1409. )
  1410. def __lt__(self, other):
  1411. """
  1412. Automatically created by attrs.
  1413. """
  1414. if other.__class__ is self.__class__:
  1415. return attrs_to_tuple(self) < attrs_to_tuple(other)
  1416. return NotImplemented
  1417. def __le__(self, other):
  1418. """
  1419. Automatically created by attrs.
  1420. """
  1421. if other.__class__ is self.__class__:
  1422. return attrs_to_tuple(self) <= attrs_to_tuple(other)
  1423. return NotImplemented
  1424. def __gt__(self, other):
  1425. """
  1426. Automatically created by attrs.
  1427. """
  1428. if other.__class__ is self.__class__:
  1429. return attrs_to_tuple(self) > attrs_to_tuple(other)
  1430. return NotImplemented
  1431. def __ge__(self, other):
  1432. """
  1433. Automatically created by attrs.
  1434. """
  1435. if other.__class__ is self.__class__:
  1436. return attrs_to_tuple(self) >= attrs_to_tuple(other)
  1437. return NotImplemented
  1438. return __lt__, __le__, __gt__, __ge__
  1439. def _add_eq(cls, attrs=None):
  1440. """
  1441. Add equality methods to *cls* with *attrs*.
  1442. """
  1443. if attrs is None:
  1444. attrs = cls.__attrs_attrs__
  1445. script, globs = _make_eq_script(attrs)
  1446. _compile_and_eval(
  1447. script, globs, filename=_generate_unique_filename(cls, "__eq__")
  1448. )
  1449. cls.__eq__ = globs["__eq__"]
  1450. cls.__ne__ = __ne__
  1451. return cls
  1452. def _make_repr_script(attrs, ns) -> tuple[str, dict]:
  1453. """
  1454. Create the source and globs for a __repr__ and return it.
  1455. """
  1456. # Figure out which attributes to include, and which function to use to
  1457. # format them. The a.repr value can be either bool or a custom
  1458. # callable.
  1459. attr_names_with_reprs = tuple(
  1460. (a.name, (repr if a.repr is True else a.repr), a.init)
  1461. for a in attrs
  1462. if a.repr is not False
  1463. )
  1464. globs = {
  1465. name + "_repr": r for name, r, _ in attr_names_with_reprs if r != repr
  1466. }
  1467. globs["_compat"] = _compat
  1468. globs["AttributeError"] = AttributeError
  1469. globs["NOTHING"] = NOTHING
  1470. attribute_fragments = []
  1471. for name, r, i in attr_names_with_reprs:
  1472. accessor = (
  1473. "self." + name if i else 'getattr(self, "' + name + '", NOTHING)'
  1474. )
  1475. fragment = (
  1476. "%s={%s!r}" % (name, accessor)
  1477. if r == repr
  1478. else "%s={%s_repr(%s)}" % (name, name, accessor)
  1479. )
  1480. attribute_fragments.append(fragment)
  1481. repr_fragment = ", ".join(attribute_fragments)
  1482. if ns is None:
  1483. cls_name_fragment = '{self.__class__.__qualname__.rsplit(">.", 1)[-1]}'
  1484. else:
  1485. cls_name_fragment = ns + ".{self.__class__.__name__}"
  1486. lines = [
  1487. "def __repr__(self):",
  1488. " try:",
  1489. " already_repring = _compat.repr_context.already_repring",
  1490. " except AttributeError:",
  1491. " already_repring = {id(self),}",
  1492. " _compat.repr_context.already_repring = already_repring",
  1493. " else:",
  1494. " if id(self) in already_repring:",
  1495. " return '...'",
  1496. " else:",
  1497. " already_repring.add(id(self))",
  1498. " try:",
  1499. f" return f'{cls_name_fragment}({repr_fragment})'",
  1500. " finally:",
  1501. " already_repring.remove(id(self))",
  1502. ]
  1503. return "\n".join(lines), globs
  1504. def _add_repr(cls, ns=None, attrs=None):
  1505. """
  1506. Add a repr method to *cls*.
  1507. """
  1508. if attrs is None:
  1509. attrs = cls.__attrs_attrs__
  1510. script, globs = _make_repr_script(attrs, ns)
  1511. _compile_and_eval(
  1512. script, globs, filename=_generate_unique_filename(cls, "__repr__")
  1513. )
  1514. cls.__repr__ = globs["__repr__"]
  1515. return cls
  1516. def fields(cls):
  1517. """
  1518. Return the tuple of *attrs* attributes for a class.
  1519. The tuple also allows accessing the fields by their names (see below for
  1520. examples).
  1521. Args:
  1522. cls (type): Class to introspect.
  1523. Raises:
  1524. TypeError: If *cls* is not a class.
  1525. attrs.exceptions.NotAnAttrsClassError:
  1526. If *cls* is not an *attrs* class.
  1527. Returns:
  1528. tuple (with name accessors) of `attrs.Attribute`
  1529. .. versionchanged:: 16.2.0 Returned tuple allows accessing the fields
  1530. by name.
  1531. .. versionchanged:: 23.1.0 Add support for generic classes.
  1532. """
  1533. generic_base = get_generic_base(cls)
  1534. if generic_base is None and not isinstance(cls, type):
  1535. msg = "Passed object must be a class."
  1536. raise TypeError(msg)
  1537. attrs = getattr(cls, "__attrs_attrs__", None)
  1538. if attrs is None:
  1539. if generic_base is not None:
  1540. attrs = getattr(generic_base, "__attrs_attrs__", None)
  1541. if attrs is not None:
  1542. # Even though this is global state, stick it on here to speed
  1543. # it up. We rely on `cls` being cached for this to be
  1544. # efficient.
  1545. cls.__attrs_attrs__ = attrs
  1546. return attrs
  1547. msg = f"{cls!r} is not an attrs-decorated class."
  1548. raise NotAnAttrsClassError(msg)
  1549. return attrs
  1550. def fields_dict(cls):
  1551. """
  1552. Return an ordered dictionary of *attrs* attributes for a class, whose keys
  1553. are the attribute names.
  1554. Args:
  1555. cls (type): Class to introspect.
  1556. Raises:
  1557. TypeError: If *cls* is not a class.
  1558. attrs.exceptions.NotAnAttrsClassError:
  1559. If *cls* is not an *attrs* class.
  1560. Returns:
  1561. dict[str, attrs.Attribute]: Dict of attribute name to definition
  1562. .. versionadded:: 18.1.0
  1563. """
  1564. if not isinstance(cls, type):
  1565. msg = "Passed object must be a class."
  1566. raise TypeError(msg)
  1567. attrs = getattr(cls, "__attrs_attrs__", None)
  1568. if attrs is None:
  1569. msg = f"{cls!r} is not an attrs-decorated class."
  1570. raise NotAnAttrsClassError(msg)
  1571. return {a.name: a for a in attrs}
  1572. def validate(inst):
  1573. """
  1574. Validate all attributes on *inst* that have a validator.
  1575. Leaves all exceptions through.
  1576. Args:
  1577. inst: Instance of a class with *attrs* attributes.
  1578. """
  1579. if _config._run_validators is False:
  1580. return
  1581. for a in fields(inst.__class__):
  1582. v = a.validator
  1583. if v is not None:
  1584. v(inst, a, getattr(inst, a.name))
  1585. def _is_slot_attr(a_name, base_attr_map):
  1586. """
  1587. Check if the attribute name comes from a slot class.
  1588. """
  1589. cls = base_attr_map.get(a_name)
  1590. return cls and "__slots__" in cls.__dict__
  1591. def _make_init_script(
  1592. cls,
  1593. attrs,
  1594. pre_init,
  1595. pre_init_has_args,
  1596. post_init,
  1597. frozen,
  1598. slots,
  1599. cache_hash,
  1600. base_attr_map,
  1601. is_exc,
  1602. cls_on_setattr,
  1603. attrs_init,
  1604. ) -> tuple[str, dict, dict]:
  1605. has_cls_on_setattr = (
  1606. cls_on_setattr is not None and cls_on_setattr is not setters.NO_OP
  1607. )
  1608. if frozen and has_cls_on_setattr:
  1609. msg = "Frozen classes can't use on_setattr."
  1610. raise ValueError(msg)
  1611. needs_cached_setattr = cache_hash or frozen
  1612. filtered_attrs = []
  1613. attr_dict = {}
  1614. for a in attrs:
  1615. if not a.init and a.default is NOTHING:
  1616. continue
  1617. filtered_attrs.append(a)
  1618. attr_dict[a.name] = a
  1619. if a.on_setattr is not None:
  1620. if frozen is True:
  1621. msg = "Frozen classes can't use on_setattr."
  1622. raise ValueError(msg)
  1623. needs_cached_setattr = True
  1624. elif has_cls_on_setattr and a.on_setattr is not setters.NO_OP:
  1625. needs_cached_setattr = True
  1626. script, globs, annotations = _attrs_to_init_script(
  1627. filtered_attrs,
  1628. frozen,
  1629. slots,
  1630. pre_init,
  1631. pre_init_has_args,
  1632. post_init,
  1633. cache_hash,
  1634. base_attr_map,
  1635. is_exc,
  1636. needs_cached_setattr,
  1637. has_cls_on_setattr,
  1638. "__attrs_init__" if attrs_init else "__init__",
  1639. )
  1640. if cls.__module__ in sys.modules:
  1641. # This makes typing.get_type_hints(CLS.__init__) resolve string types.
  1642. globs.update(sys.modules[cls.__module__].__dict__)
  1643. globs.update({"NOTHING": NOTHING, "attr_dict": attr_dict})
  1644. if needs_cached_setattr:
  1645. # Save the lookup overhead in __init__ if we need to circumvent
  1646. # setattr hooks.
  1647. globs["_cached_setattr_get"] = _OBJ_SETATTR.__get__
  1648. return script, globs, annotations
  1649. def _setattr(attr_name: str, value_var: str, has_on_setattr: bool) -> str:
  1650. """
  1651. Use the cached object.setattr to set *attr_name* to *value_var*.
  1652. """
  1653. return f"_setattr('{attr_name}', {value_var})"
  1654. def _setattr_with_converter(
  1655. attr_name: str, value_var: str, has_on_setattr: bool, converter: Converter
  1656. ) -> str:
  1657. """
  1658. Use the cached object.setattr to set *attr_name* to *value_var*, but run
  1659. its converter first.
  1660. """
  1661. return f"_setattr('{attr_name}', {converter._fmt_converter_call(attr_name, value_var)})"
  1662. def _assign(attr_name: str, value: str, has_on_setattr: bool) -> str:
  1663. """
  1664. Unless *attr_name* has an on_setattr hook, use normal assignment. Otherwise
  1665. relegate to _setattr.
  1666. """
  1667. if has_on_setattr:
  1668. return _setattr(attr_name, value, True)
  1669. return f"self.{attr_name} = {value}"
  1670. def _assign_with_converter(
  1671. attr_name: str, value_var: str, has_on_setattr: bool, converter: Converter
  1672. ) -> str:
  1673. """
  1674. Unless *attr_name* has an on_setattr hook, use normal assignment after
  1675. conversion. Otherwise relegate to _setattr_with_converter.
  1676. """
  1677. if has_on_setattr:
  1678. return _setattr_with_converter(attr_name, value_var, True, converter)
  1679. return f"self.{attr_name} = {converter._fmt_converter_call(attr_name, value_var)}"
  1680. def _determine_setters(
  1681. frozen: bool, slots: bool, base_attr_map: dict[str, type]
  1682. ):
  1683. """
  1684. Determine the correct setter functions based on whether a class is frozen
  1685. and/or slotted.
  1686. """
  1687. if frozen is True:
  1688. if slots is True:
  1689. return (), _setattr, _setattr_with_converter
  1690. # Dict frozen classes assign directly to __dict__.
  1691. # But only if the attribute doesn't come from an ancestor slot
  1692. # class.
  1693. # Note _inst_dict will be used again below if cache_hash is True
  1694. def fmt_setter(
  1695. attr_name: str, value_var: str, has_on_setattr: bool
  1696. ) -> str:
  1697. if _is_slot_attr(attr_name, base_attr_map):
  1698. return _setattr(attr_name, value_var, has_on_setattr)
  1699. return f"_inst_dict['{attr_name}'] = {value_var}"
  1700. def fmt_setter_with_converter(
  1701. attr_name: str,
  1702. value_var: str,
  1703. has_on_setattr: bool,
  1704. converter: Converter,
  1705. ) -> str:
  1706. if has_on_setattr or _is_slot_attr(attr_name, base_attr_map):
  1707. return _setattr_with_converter(
  1708. attr_name, value_var, has_on_setattr, converter
  1709. )
  1710. return f"_inst_dict['{attr_name}'] = {converter._fmt_converter_call(attr_name, value_var)}"
  1711. return (
  1712. ("_inst_dict = self.__dict__",),
  1713. fmt_setter,
  1714. fmt_setter_with_converter,
  1715. )
  1716. # Not frozen -- we can just assign directly.
  1717. return (), _assign, _assign_with_converter
  1718. def _attrs_to_init_script(
  1719. attrs: list[Attribute],
  1720. is_frozen: bool,
  1721. is_slotted: bool,
  1722. call_pre_init: bool,
  1723. pre_init_has_args: bool,
  1724. call_post_init: bool,
  1725. does_cache_hash: bool,
  1726. base_attr_map: dict[str, type],
  1727. is_exc: bool,
  1728. needs_cached_setattr: bool,
  1729. has_cls_on_setattr: bool,
  1730. method_name: str,
  1731. ) -> tuple[str, dict, dict]:
  1732. """
  1733. Return a script of an initializer for *attrs*, a dict of globals, and
  1734. annotations for the initializer.
  1735. The globals are required by the generated script.
  1736. """
  1737. lines = ["self.__attrs_pre_init__()"] if call_pre_init else []
  1738. if needs_cached_setattr:
  1739. lines.append(
  1740. # Circumvent the __setattr__ descriptor to save one lookup per
  1741. # assignment. Note _setattr will be used again below if
  1742. # does_cache_hash is True.
  1743. "_setattr = _cached_setattr_get(self)"
  1744. )
  1745. extra_lines, fmt_setter, fmt_setter_with_converter = _determine_setters(
  1746. is_frozen, is_slotted, base_attr_map
  1747. )
  1748. lines.extend(extra_lines)
  1749. args = []
  1750. kw_only_args = []
  1751. attrs_to_validate = []
  1752. # This is a dictionary of names to validator and converter callables.
  1753. # Injecting this into __init__ globals lets us avoid lookups.
  1754. names_for_globals = {}
  1755. annotations = {"return": None}
  1756. for a in attrs:
  1757. if a.validator:
  1758. attrs_to_validate.append(a)
  1759. attr_name = a.name
  1760. has_on_setattr = a.on_setattr is not None or (
  1761. a.on_setattr is not setters.NO_OP and has_cls_on_setattr
  1762. )
  1763. # a.alias is set to maybe-mangled attr_name in _ClassBuilder if not
  1764. # explicitly provided
  1765. arg_name = a.alias
  1766. has_factory = isinstance(a.default, Factory)
  1767. maybe_self = "self" if has_factory and a.default.takes_self else ""
  1768. if a.converter is not None and not isinstance(a.converter, Converter):
  1769. converter = Converter(a.converter)
  1770. else:
  1771. converter = a.converter
  1772. if a.init is False:
  1773. if has_factory:
  1774. init_factory_name = _INIT_FACTORY_PAT % (a.name,)
  1775. if converter is not None:
  1776. lines.append(
  1777. fmt_setter_with_converter(
  1778. attr_name,
  1779. init_factory_name + f"({maybe_self})",
  1780. has_on_setattr,
  1781. converter,
  1782. )
  1783. )
  1784. names_for_globals[converter._get_global_name(a.name)] = (
  1785. converter.converter
  1786. )
  1787. else:
  1788. lines.append(
  1789. fmt_setter(
  1790. attr_name,
  1791. init_factory_name + f"({maybe_self})",
  1792. has_on_setattr,
  1793. )
  1794. )
  1795. names_for_globals[init_factory_name] = a.default.factory
  1796. elif converter is not None:
  1797. lines.append(
  1798. fmt_setter_with_converter(
  1799. attr_name,
  1800. f"attr_dict['{attr_name}'].default",
  1801. has_on_setattr,
  1802. converter,
  1803. )
  1804. )
  1805. names_for_globals[converter._get_global_name(a.name)] = (
  1806. converter.converter
  1807. )
  1808. else:
  1809. lines.append(
  1810. fmt_setter(
  1811. attr_name,
  1812. f"attr_dict['{attr_name}'].default",
  1813. has_on_setattr,
  1814. )
  1815. )
  1816. elif a.default is not NOTHING and not has_factory:
  1817. arg = f"{arg_name}=attr_dict['{attr_name}'].default"
  1818. if a.kw_only:
  1819. kw_only_args.append(arg)
  1820. else:
  1821. args.append(arg)
  1822. if converter is not None:
  1823. lines.append(
  1824. fmt_setter_with_converter(
  1825. attr_name, arg_name, has_on_setattr, converter
  1826. )
  1827. )
  1828. names_for_globals[converter._get_global_name(a.name)] = (
  1829. converter.converter
  1830. )
  1831. else:
  1832. lines.append(fmt_setter(attr_name, arg_name, has_on_setattr))
  1833. elif has_factory:
  1834. arg = f"{arg_name}=NOTHING"
  1835. if a.kw_only:
  1836. kw_only_args.append(arg)
  1837. else:
  1838. args.append(arg)
  1839. lines.append(f"if {arg_name} is not NOTHING:")
  1840. init_factory_name = _INIT_FACTORY_PAT % (a.name,)
  1841. if converter is not None:
  1842. lines.append(
  1843. " "
  1844. + fmt_setter_with_converter(
  1845. attr_name, arg_name, has_on_setattr, converter
  1846. )
  1847. )
  1848. lines.append("else:")
  1849. lines.append(
  1850. " "
  1851. + fmt_setter_with_converter(
  1852. attr_name,
  1853. init_factory_name + "(" + maybe_self + ")",
  1854. has_on_setattr,
  1855. converter,
  1856. )
  1857. )
  1858. names_for_globals[converter._get_global_name(a.name)] = (
  1859. converter.converter
  1860. )
  1861. else:
  1862. lines.append(
  1863. " " + fmt_setter(attr_name, arg_name, has_on_setattr)
  1864. )
  1865. lines.append("else:")
  1866. lines.append(
  1867. " "
  1868. + fmt_setter(
  1869. attr_name,
  1870. init_factory_name + "(" + maybe_self + ")",
  1871. has_on_setattr,
  1872. )
  1873. )
  1874. names_for_globals[init_factory_name] = a.default.factory
  1875. else:
  1876. if a.kw_only:
  1877. kw_only_args.append(arg_name)
  1878. else:
  1879. args.append(arg_name)
  1880. if converter is not None:
  1881. lines.append(
  1882. fmt_setter_with_converter(
  1883. attr_name, arg_name, has_on_setattr, converter
  1884. )
  1885. )
  1886. names_for_globals[converter._get_global_name(a.name)] = (
  1887. converter.converter
  1888. )
  1889. else:
  1890. lines.append(fmt_setter(attr_name, arg_name, has_on_setattr))
  1891. if a.init is True:
  1892. if a.type is not None and converter is None:
  1893. annotations[arg_name] = a.type
  1894. elif converter is not None and converter._first_param_type:
  1895. # Use the type from the converter if present.
  1896. annotations[arg_name] = converter._first_param_type
  1897. if attrs_to_validate: # we can skip this if there are no validators.
  1898. names_for_globals["_config"] = _config
  1899. lines.append("if _config._run_validators is True:")
  1900. for a in attrs_to_validate:
  1901. val_name = "__attr_validator_" + a.name
  1902. attr_name = "__attr_" + a.name
  1903. lines.append(f" {val_name}(self, {attr_name}, self.{a.name})")
  1904. names_for_globals[val_name] = a.validator
  1905. names_for_globals[attr_name] = a
  1906. if call_post_init:
  1907. lines.append("self.__attrs_post_init__()")
  1908. # Because this is set only after __attrs_post_init__ is called, a crash
  1909. # will result if post-init tries to access the hash code. This seemed
  1910. # preferable to setting this beforehand, in which case alteration to field
  1911. # values during post-init combined with post-init accessing the hash code
  1912. # would result in silent bugs.
  1913. if does_cache_hash:
  1914. if is_frozen:
  1915. if is_slotted:
  1916. init_hash_cache = f"_setattr('{_HASH_CACHE_FIELD}', None)"
  1917. else:
  1918. init_hash_cache = f"_inst_dict['{_HASH_CACHE_FIELD}'] = None"
  1919. else:
  1920. init_hash_cache = f"self.{_HASH_CACHE_FIELD} = None"
  1921. lines.append(init_hash_cache)
  1922. # For exceptions we rely on BaseException.__init__ for proper
  1923. # initialization.
  1924. if is_exc:
  1925. vals = ",".join(f"self.{a.name}" for a in attrs if a.init)
  1926. lines.append(f"BaseException.__init__(self, {vals})")
  1927. args = ", ".join(args)
  1928. pre_init_args = args
  1929. if kw_only_args:
  1930. # leading comma & kw_only args
  1931. args += f"{', ' if args else ''}*, {', '.join(kw_only_args)}"
  1932. pre_init_kw_only_args = ", ".join(
  1933. [
  1934. f"{kw_arg_name}={kw_arg_name}"
  1935. # We need to remove the defaults from the kw_only_args.
  1936. for kw_arg_name in (kwa.split("=")[0] for kwa in kw_only_args)
  1937. ]
  1938. )
  1939. pre_init_args += ", " if pre_init_args else ""
  1940. pre_init_args += pre_init_kw_only_args
  1941. if call_pre_init and pre_init_has_args:
  1942. # If pre init method has arguments, pass same arguments as `__init__`.
  1943. lines[0] = f"self.__attrs_pre_init__({pre_init_args})"
  1944. # Python <3.12 doesn't allow backslashes in f-strings.
  1945. NL = "\n "
  1946. return (
  1947. f"""def {method_name}(self, {args}):
  1948. {NL.join(lines) if lines else "pass"}
  1949. """,
  1950. names_for_globals,
  1951. annotations,
  1952. )
  1953. def _default_init_alias_for(name: str) -> str:
  1954. """
  1955. The default __init__ parameter name for a field.
  1956. This performs private-name adjustment via leading-unscore stripping,
  1957. and is the default value of Attribute.alias if not provided.
  1958. """
  1959. return name.lstrip("_")
  1960. class Attribute:
  1961. """
  1962. *Read-only* representation of an attribute.
  1963. .. warning::
  1964. You should never instantiate this class yourself.
  1965. The class has *all* arguments of `attr.ib` (except for ``factory`` which is
  1966. only syntactic sugar for ``default=Factory(...)`` plus the following:
  1967. - ``name`` (`str`): The name of the attribute.
  1968. - ``alias`` (`str`): The __init__ parameter name of the attribute, after
  1969. any explicit overrides and default private-attribute-name handling.
  1970. - ``inherited`` (`bool`): Whether or not that attribute has been inherited
  1971. from a base class.
  1972. - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The
  1973. callables that are used for comparing and ordering objects by this
  1974. attribute, respectively. These are set by passing a callable to
  1975. `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also
  1976. :ref:`comparison customization <custom-comparison>`.
  1977. Instances of this class are frequently used for introspection purposes
  1978. like:
  1979. - `fields` returns a tuple of them.
  1980. - Validators get them passed as the first argument.
  1981. - The :ref:`field transformer <transform-fields>` hook receives a list of
  1982. them.
  1983. - The ``alias`` property exposes the __init__ parameter name of the field,
  1984. with any overrides and default private-attribute handling applied.
  1985. .. versionadded:: 20.1.0 *inherited*
  1986. .. versionadded:: 20.1.0 *on_setattr*
  1987. .. versionchanged:: 20.2.0 *inherited* is not taken into account for
  1988. equality checks and hashing anymore.
  1989. .. versionadded:: 21.1.0 *eq_key* and *order_key*
  1990. .. versionadded:: 22.2.0 *alias*
  1991. For the full version history of the fields, see `attr.ib`.
  1992. """
  1993. # These slots must NOT be reordered because we use them later for
  1994. # instantiation.
  1995. __slots__ = ( # noqa: RUF023
  1996. "name",
  1997. "default",
  1998. "validator",
  1999. "repr",
  2000. "eq",
  2001. "eq_key",
  2002. "order",
  2003. "order_key",
  2004. "hash",
  2005. "init",
  2006. "metadata",
  2007. "type",
  2008. "converter",
  2009. "kw_only",
  2010. "inherited",
  2011. "on_setattr",
  2012. "alias",
  2013. )
  2014. def __init__(
  2015. self,
  2016. name,
  2017. default,
  2018. validator,
  2019. repr,
  2020. cmp, # XXX: unused, remove along with other cmp code.
  2021. hash,
  2022. init,
  2023. inherited,
  2024. metadata=None,
  2025. type=None,
  2026. converter=None,
  2027. kw_only=False,
  2028. eq=None,
  2029. eq_key=None,
  2030. order=None,
  2031. order_key=None,
  2032. on_setattr=None,
  2033. alias=None,
  2034. ):
  2035. eq, eq_key, order, order_key = _determine_attrib_eq_order(
  2036. cmp, eq_key or eq, order_key or order, True
  2037. )
  2038. # Cache this descriptor here to speed things up later.
  2039. bound_setattr = _OBJ_SETATTR.__get__(self)
  2040. # Despite the big red warning, people *do* instantiate `Attribute`
  2041. # themselves.
  2042. bound_setattr("name", name)
  2043. bound_setattr("default", default)
  2044. bound_setattr("validator", validator)
  2045. bound_setattr("repr", repr)
  2046. bound_setattr("eq", eq)
  2047. bound_setattr("eq_key", eq_key)
  2048. bound_setattr("order", order)
  2049. bound_setattr("order_key", order_key)
  2050. bound_setattr("hash", hash)
  2051. bound_setattr("init", init)
  2052. bound_setattr("converter", converter)
  2053. bound_setattr(
  2054. "metadata",
  2055. (
  2056. types.MappingProxyType(dict(metadata)) # Shallow copy
  2057. if metadata
  2058. else _EMPTY_METADATA_SINGLETON
  2059. ),
  2060. )
  2061. bound_setattr("type", type)
  2062. bound_setattr("kw_only", kw_only)
  2063. bound_setattr("inherited", inherited)
  2064. bound_setattr("on_setattr", on_setattr)
  2065. bound_setattr("alias", alias)
  2066. def __setattr__(self, name, value):
  2067. raise FrozenInstanceError
  2068. @classmethod
  2069. def from_counting_attr(cls, name: str, ca: _CountingAttr, type=None):
  2070. # type holds the annotated value. deal with conflicts:
  2071. if type is None:
  2072. type = ca.type
  2073. elif ca.type is not None:
  2074. msg = f"Type annotation and type argument cannot both be present for '{name}'."
  2075. raise ValueError(msg)
  2076. return cls(
  2077. name,
  2078. ca._default,
  2079. ca._validator,
  2080. ca.repr,
  2081. None,
  2082. ca.hash,
  2083. ca.init,
  2084. False,
  2085. ca.metadata,
  2086. type,
  2087. ca.converter,
  2088. ca.kw_only,
  2089. ca.eq,
  2090. ca.eq_key,
  2091. ca.order,
  2092. ca.order_key,
  2093. ca.on_setattr,
  2094. ca.alias,
  2095. )
  2096. # Don't use attrs.evolve since fields(Attribute) doesn't work
  2097. def evolve(self, **changes):
  2098. """
  2099. Copy *self* and apply *changes*.
  2100. This works similarly to `attrs.evolve` but that function does not work
  2101. with :class:`attrs.Attribute`.
  2102. It is mainly meant to be used for `transform-fields`.
  2103. .. versionadded:: 20.3.0
  2104. """
  2105. new = copy.copy(self)
  2106. new._setattrs(changes.items())
  2107. return new
  2108. # Don't use _add_pickle since fields(Attribute) doesn't work
  2109. def __getstate__(self):
  2110. """
  2111. Play nice with pickle.
  2112. """
  2113. return tuple(
  2114. getattr(self, name) if name != "metadata" else dict(self.metadata)
  2115. for name in self.__slots__
  2116. )
  2117. def __setstate__(self, state):
  2118. """
  2119. Play nice with pickle.
  2120. """
  2121. self._setattrs(zip(self.__slots__, state))
  2122. def _setattrs(self, name_values_pairs):
  2123. bound_setattr = _OBJ_SETATTR.__get__(self)
  2124. for name, value in name_values_pairs:
  2125. if name != "metadata":
  2126. bound_setattr(name, value)
  2127. else:
  2128. bound_setattr(
  2129. name,
  2130. (
  2131. types.MappingProxyType(dict(value))
  2132. if value
  2133. else _EMPTY_METADATA_SINGLETON
  2134. ),
  2135. )
  2136. _a = [
  2137. Attribute(
  2138. name=name,
  2139. default=NOTHING,
  2140. validator=None,
  2141. repr=True,
  2142. cmp=None,
  2143. eq=True,
  2144. order=False,
  2145. hash=(name != "metadata"),
  2146. init=True,
  2147. inherited=False,
  2148. alias=_default_init_alias_for(name),
  2149. )
  2150. for name in Attribute.__slots__
  2151. ]
  2152. Attribute = _add_hash(
  2153. _add_eq(
  2154. _add_repr(Attribute, attrs=_a),
  2155. attrs=[a for a in _a if a.name != "inherited"],
  2156. ),
  2157. attrs=[a for a in _a if a.hash and a.name != "inherited"],
  2158. )
  2159. class _CountingAttr:
  2160. """
  2161. Intermediate representation of attributes that uses a counter to preserve
  2162. the order in which the attributes have been defined.
  2163. *Internal* data structure of the attrs library. Running into is most
  2164. likely the result of a bug like a forgotten `@attr.s` decorator.
  2165. """
  2166. __slots__ = (
  2167. "_default",
  2168. "_validator",
  2169. "alias",
  2170. "converter",
  2171. "counter",
  2172. "eq",
  2173. "eq_key",
  2174. "hash",
  2175. "init",
  2176. "kw_only",
  2177. "metadata",
  2178. "on_setattr",
  2179. "order",
  2180. "order_key",
  2181. "repr",
  2182. "type",
  2183. )
  2184. __attrs_attrs__ = (
  2185. *tuple(
  2186. Attribute(
  2187. name=name,
  2188. alias=_default_init_alias_for(name),
  2189. default=NOTHING,
  2190. validator=None,
  2191. repr=True,
  2192. cmp=None,
  2193. hash=True,
  2194. init=True,
  2195. kw_only=False,
  2196. eq=True,
  2197. eq_key=None,
  2198. order=False,
  2199. order_key=None,
  2200. inherited=False,
  2201. on_setattr=None,
  2202. )
  2203. for name in (
  2204. "counter",
  2205. "_default",
  2206. "repr",
  2207. "eq",
  2208. "order",
  2209. "hash",
  2210. "init",
  2211. "on_setattr",
  2212. "alias",
  2213. )
  2214. ),
  2215. Attribute(
  2216. name="metadata",
  2217. alias="metadata",
  2218. default=None,
  2219. validator=None,
  2220. repr=True,
  2221. cmp=None,
  2222. hash=False,
  2223. init=True,
  2224. kw_only=False,
  2225. eq=True,
  2226. eq_key=None,
  2227. order=False,
  2228. order_key=None,
  2229. inherited=False,
  2230. on_setattr=None,
  2231. ),
  2232. )
  2233. cls_counter = 0
  2234. def __init__(
  2235. self,
  2236. default,
  2237. validator,
  2238. repr,
  2239. cmp,
  2240. hash,
  2241. init,
  2242. converter,
  2243. metadata,
  2244. type,
  2245. kw_only,
  2246. eq,
  2247. eq_key,
  2248. order,
  2249. order_key,
  2250. on_setattr,
  2251. alias,
  2252. ):
  2253. _CountingAttr.cls_counter += 1
  2254. self.counter = _CountingAttr.cls_counter
  2255. self._default = default
  2256. self._validator = validator
  2257. self.converter = converter
  2258. self.repr = repr
  2259. self.eq = eq
  2260. self.eq_key = eq_key
  2261. self.order = order
  2262. self.order_key = order_key
  2263. self.hash = hash
  2264. self.init = init
  2265. self.metadata = metadata
  2266. self.type = type
  2267. self.kw_only = kw_only
  2268. self.on_setattr = on_setattr
  2269. self.alias = alias
  2270. def validator(self, meth):
  2271. """
  2272. Decorator that adds *meth* to the list of validators.
  2273. Returns *meth* unchanged.
  2274. .. versionadded:: 17.1.0
  2275. """
  2276. if self._validator is None:
  2277. self._validator = meth
  2278. else:
  2279. self._validator = and_(self._validator, meth)
  2280. return meth
  2281. def default(self, meth):
  2282. """
  2283. Decorator that allows to set the default for an attribute.
  2284. Returns *meth* unchanged.
  2285. Raises:
  2286. DefaultAlreadySetError: If default has been set before.
  2287. .. versionadded:: 17.1.0
  2288. """
  2289. if self._default is not NOTHING:
  2290. raise DefaultAlreadySetError
  2291. self._default = Factory(meth, takes_self=True)
  2292. return meth
  2293. _CountingAttr = _add_eq(_add_repr(_CountingAttr))
  2294. class Factory:
  2295. """
  2296. Stores a factory callable.
  2297. If passed as the default value to `attrs.field`, the factory is used to
  2298. generate a new value.
  2299. Args:
  2300. factory (typing.Callable):
  2301. A callable that takes either none or exactly one mandatory
  2302. positional argument depending on *takes_self*.
  2303. takes_self (bool):
  2304. Pass the partially initialized instance that is being initialized
  2305. as a positional argument.
  2306. .. versionadded:: 17.1.0 *takes_self*
  2307. """
  2308. __slots__ = ("factory", "takes_self")
  2309. def __init__(self, factory, takes_self=False):
  2310. self.factory = factory
  2311. self.takes_self = takes_self
  2312. def __getstate__(self):
  2313. """
  2314. Play nice with pickle.
  2315. """
  2316. return tuple(getattr(self, name) for name in self.__slots__)
  2317. def __setstate__(self, state):
  2318. """
  2319. Play nice with pickle.
  2320. """
  2321. for name, value in zip(self.__slots__, state):
  2322. setattr(self, name, value)
  2323. _f = [
  2324. Attribute(
  2325. name=name,
  2326. default=NOTHING,
  2327. validator=None,
  2328. repr=True,
  2329. cmp=None,
  2330. eq=True,
  2331. order=False,
  2332. hash=True,
  2333. init=True,
  2334. inherited=False,
  2335. )
  2336. for name in Factory.__slots__
  2337. ]
  2338. Factory = _add_hash(_add_eq(_add_repr(Factory, attrs=_f), attrs=_f), attrs=_f)
  2339. class Converter:
  2340. """
  2341. Stores a converter callable.
  2342. Allows for the wrapped converter to take additional arguments. The
  2343. arguments are passed in the order they are documented.
  2344. Args:
  2345. converter (Callable): A callable that converts the passed value.
  2346. takes_self (bool):
  2347. Pass the partially initialized instance that is being initialized
  2348. as a positional argument. (default: `False`)
  2349. takes_field (bool):
  2350. Pass the field definition (an :class:`Attribute`) into the
  2351. converter as a positional argument. (default: `False`)
  2352. .. versionadded:: 24.1.0
  2353. """
  2354. __slots__ = (
  2355. "__call__",
  2356. "_first_param_type",
  2357. "_global_name",
  2358. "converter",
  2359. "takes_field",
  2360. "takes_self",
  2361. )
  2362. def __init__(self, converter, *, takes_self=False, takes_field=False):
  2363. self.converter = converter
  2364. self.takes_self = takes_self
  2365. self.takes_field = takes_field
  2366. ex = _AnnotationExtractor(converter)
  2367. self._first_param_type = ex.get_first_param_type()
  2368. if not (self.takes_self or self.takes_field):
  2369. self.__call__ = lambda value, _, __: self.converter(value)
  2370. elif self.takes_self and not self.takes_field:
  2371. self.__call__ = lambda value, instance, __: self.converter(
  2372. value, instance
  2373. )
  2374. elif not self.takes_self and self.takes_field:
  2375. self.__call__ = lambda value, __, field: self.converter(
  2376. value, field
  2377. )
  2378. else:
  2379. self.__call__ = lambda value, instance, field: self.converter(
  2380. value, instance, field
  2381. )
  2382. rt = ex.get_return_type()
  2383. if rt is not None:
  2384. self.__call__.__annotations__["return"] = rt
  2385. @staticmethod
  2386. def _get_global_name(attr_name: str) -> str:
  2387. """
  2388. Return the name that a converter for an attribute name *attr_name*
  2389. would have.
  2390. """
  2391. return f"__attr_converter_{attr_name}"
  2392. def _fmt_converter_call(self, attr_name: str, value_var: str) -> str:
  2393. """
  2394. Return a string that calls the converter for an attribute name
  2395. *attr_name* and the value in variable named *value_var* according to
  2396. `self.takes_self` and `self.takes_field`.
  2397. """
  2398. if not (self.takes_self or self.takes_field):
  2399. return f"{self._get_global_name(attr_name)}({value_var})"
  2400. if self.takes_self and self.takes_field:
  2401. return f"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])"
  2402. if self.takes_self:
  2403. return f"{self._get_global_name(attr_name)}({value_var}, self)"
  2404. return f"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])"
  2405. def __getstate__(self):
  2406. """
  2407. Return a dict containing only converter and takes_self -- the rest gets
  2408. computed when loading.
  2409. """
  2410. return {
  2411. "converter": self.converter,
  2412. "takes_self": self.takes_self,
  2413. "takes_field": self.takes_field,
  2414. }
  2415. def __setstate__(self, state):
  2416. """
  2417. Load instance from state.
  2418. """
  2419. self.__init__(**state)
  2420. _f = [
  2421. Attribute(
  2422. name=name,
  2423. default=NOTHING,
  2424. validator=None,
  2425. repr=True,
  2426. cmp=None,
  2427. eq=True,
  2428. order=False,
  2429. hash=True,
  2430. init=True,
  2431. inherited=False,
  2432. )
  2433. for name in ("converter", "takes_self", "takes_field")
  2434. ]
  2435. Converter = _add_hash(
  2436. _add_eq(_add_repr(Converter, attrs=_f), attrs=_f), attrs=_f
  2437. )
  2438. def make_class(
  2439. name, attrs, bases=(object,), class_body=None, **attributes_arguments
  2440. ):
  2441. r"""
  2442. A quick way to create a new class called *name* with *attrs*.
  2443. .. note::
  2444. ``make_class()`` is a thin wrapper around `attr.s`, not `attrs.define`
  2445. which means that it doesn't come with some of the improved defaults.
  2446. For example, if you want the same ``on_setattr`` behavior as in
  2447. `attrs.define`, you have to pass the hooks yourself: ``make_class(...,
  2448. on_setattr=setters.pipe(setters.convert, setters.validate)``
  2449. .. warning::
  2450. It is *your* duty to ensure that the class name and the attribute names
  2451. are valid identifiers. ``make_class()`` will *not* validate them for
  2452. you.
  2453. Args:
  2454. name (str): The name for the new class.
  2455. attrs (list | dict):
  2456. A list of names or a dictionary of mappings of names to `attr.ib`\
  2457. s / `attrs.field`\ s.
  2458. The order is deduced from the order of the names or attributes
  2459. inside *attrs*. Otherwise the order of the definition of the
  2460. attributes is used.
  2461. bases (tuple[type, ...]): Classes that the new class will subclass.
  2462. class_body (dict):
  2463. An optional dictionary of class attributes for the new class.
  2464. attributes_arguments: Passed unmodified to `attr.s`.
  2465. Returns:
  2466. type: A new class with *attrs*.
  2467. .. versionadded:: 17.1.0 *bases*
  2468. .. versionchanged:: 18.1.0 If *attrs* is ordered, the order is retained.
  2469. .. versionchanged:: 23.2.0 *class_body*
  2470. .. versionchanged:: 25.2.0 Class names can now be unicode.
  2471. """
  2472. # Class identifiers are converted into the normal form NFKC while parsing
  2473. name = unicodedata.normalize("NFKC", name)
  2474. if isinstance(attrs, dict):
  2475. cls_dict = attrs
  2476. elif isinstance(attrs, (list, tuple)):
  2477. cls_dict = {a: attrib() for a in attrs}
  2478. else:
  2479. msg = "attrs argument must be a dict or a list."
  2480. raise TypeError(msg)
  2481. pre_init = cls_dict.pop("__attrs_pre_init__", None)
  2482. post_init = cls_dict.pop("__attrs_post_init__", None)
  2483. user_init = cls_dict.pop("__init__", None)
  2484. body = {}
  2485. if class_body is not None:
  2486. body.update(class_body)
  2487. if pre_init is not None:
  2488. body["__attrs_pre_init__"] = pre_init
  2489. if post_init is not None:
  2490. body["__attrs_post_init__"] = post_init
  2491. if user_init is not None:
  2492. body["__init__"] = user_init
  2493. type_ = types.new_class(name, bases, {}, lambda ns: ns.update(body))
  2494. # For pickling to work, the __module__ variable needs to be set to the
  2495. # frame where the class is created. Bypass this step in environments where
  2496. # sys._getframe is not defined (Jython for example) or sys._getframe is not
  2497. # defined for arguments greater than 0 (IronPython).
  2498. with contextlib.suppress(AttributeError, ValueError):
  2499. type_.__module__ = sys._getframe(1).f_globals.get(
  2500. "__name__", "__main__"
  2501. )
  2502. # We do it here for proper warnings with meaningful stacklevel.
  2503. cmp = attributes_arguments.pop("cmp", None)
  2504. (
  2505. attributes_arguments["eq"],
  2506. attributes_arguments["order"],
  2507. ) = _determine_attrs_eq_order(
  2508. cmp,
  2509. attributes_arguments.get("eq"),
  2510. attributes_arguments.get("order"),
  2511. True,
  2512. )
  2513. cls = _attrs(these=cls_dict, **attributes_arguments)(type_)
  2514. # Only add type annotations now or "_attrs()" will complain:
  2515. cls.__annotations__ = {
  2516. k: v.type for k, v in cls_dict.items() if v.type is not None
  2517. }
  2518. return cls
  2519. # These are required by within this module so we define them here and merely
  2520. # import into .validators / .converters.
  2521. @attrs(slots=True, unsafe_hash=True)
  2522. class _AndValidator:
  2523. """
  2524. Compose many validators to a single one.
  2525. """
  2526. _validators = attrib()
  2527. def __call__(self, inst, attr, value):
  2528. for v in self._validators:
  2529. v(inst, attr, value)
  2530. def and_(*validators):
  2531. """
  2532. A validator that composes multiple validators into one.
  2533. When called on a value, it runs all wrapped validators.
  2534. Args:
  2535. validators (~collections.abc.Iterable[typing.Callable]):
  2536. Arbitrary number of validators.
  2537. .. versionadded:: 17.1.0
  2538. """
  2539. vals = []
  2540. for validator in validators:
  2541. vals.extend(
  2542. validator._validators
  2543. if isinstance(validator, _AndValidator)
  2544. else [validator]
  2545. )
  2546. return _AndValidator(tuple(vals))
  2547. def pipe(*converters):
  2548. """
  2549. A converter that composes multiple converters into one.
  2550. When called on a value, it runs all wrapped converters, returning the
  2551. *last* value.
  2552. Type annotations will be inferred from the wrapped converters', if they
  2553. have any.
  2554. converters (~collections.abc.Iterable[typing.Callable]):
  2555. Arbitrary number of converters.
  2556. .. versionadded:: 20.1.0
  2557. """
  2558. return_instance = any(isinstance(c, Converter) for c in converters)
  2559. if return_instance:
  2560. def pipe_converter(val, inst, field):
  2561. for c in converters:
  2562. val = (
  2563. c(val, inst, field) if isinstance(c, Converter) else c(val)
  2564. )
  2565. return val
  2566. else:
  2567. def pipe_converter(val):
  2568. for c in converters:
  2569. val = c(val)
  2570. return val
  2571. if not converters:
  2572. # If the converter list is empty, pipe_converter is the identity.
  2573. A = TypeVar("A")
  2574. pipe_converter.__annotations__.update({"val": A, "return": A})
  2575. else:
  2576. # Get parameter type from first converter.
  2577. t = _AnnotationExtractor(converters[0]).get_first_param_type()
  2578. if t:
  2579. pipe_converter.__annotations__["val"] = t
  2580. last = converters[-1]
  2581. if not PY_3_11_PLUS and isinstance(last, Converter):
  2582. last = last.__call__
  2583. # Get return type from last converter.
  2584. rt = _AnnotationExtractor(last).get_return_type()
  2585. if rt:
  2586. pipe_converter.__annotations__["return"] = rt
  2587. if return_instance:
  2588. return Converter(pipe_converter, takes_self=True, takes_field=True)
  2589. return pipe_converter