_make.py 104 KB

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