Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_make.py 95KB

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