_make.py 100 KB

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