_make.py 100 KB

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