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

_make.py 69KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168
  1. from __future__ import absolute_import, division, print_function
  2. import copy
  3. import linecache
  4. import sys
  5. import threading
  6. import uuid
  7. import warnings
  8. from operator import itemgetter
  9. from . import _config
  10. from ._compat import (
  11. PY2,
  12. isclass,
  13. iteritems,
  14. metadata_proxy,
  15. ordered_dict,
  16. set_closure_cell,
  17. )
  18. from .exceptions import (
  19. DefaultAlreadySetError,
  20. FrozenInstanceError,
  21. NotAnAttrsClassError,
  22. PythonTooOldError,
  23. UnannotatedAttributeError,
  24. )
  25. # This is used at least twice, so cache it here.
  26. _obj_setattr = object.__setattr__
  27. _init_converter_pat = "__attr_converter_{}"
  28. _init_factory_pat = "__attr_factory_{}"
  29. _tuple_property_pat = (
  30. " {attr_name} = _attrs_property(_attrs_itemgetter({index}))"
  31. )
  32. _classvar_prefixes = ("typing.ClassVar", "t.ClassVar", "ClassVar")
  33. # we don't use a double-underscore prefix because that triggers
  34. # name mangling when trying to create a slot for the field
  35. # (when slots=True)
  36. _hash_cache_field = "_attrs_cached_hash"
  37. _empty_metadata_singleton = metadata_proxy({})
  38. # Unique object for unequivocal getattr() defaults.
  39. _sentinel = object()
  40. class _Nothing(object):
  41. """
  42. Sentinel class to indicate the lack of a value when ``None`` is ambiguous.
  43. ``_Nothing`` is a singleton. There is only ever one of it.
  44. """
  45. _singleton = None
  46. def __new__(cls):
  47. if _Nothing._singleton is None:
  48. _Nothing._singleton = super(_Nothing, cls).__new__(cls)
  49. return _Nothing._singleton
  50. def __repr__(self):
  51. return "NOTHING"
  52. NOTHING = _Nothing()
  53. """
  54. Sentinel to indicate the lack of a value when ``None`` is ambiguous.
  55. """
  56. def attrib(
  57. default=NOTHING,
  58. validator=None,
  59. repr=True,
  60. cmp=None,
  61. hash=None,
  62. init=True,
  63. metadata=None,
  64. type=None,
  65. converter=None,
  66. factory=None,
  67. kw_only=False,
  68. eq=None,
  69. order=None,
  70. ):
  71. """
  72. Create a new attribute on a class.
  73. .. warning::
  74. Does *not* do anything unless the class is also decorated with
  75. `attr.s`!
  76. :param default: A value that is used if an ``attrs``-generated ``__init__``
  77. is used and no value is passed while instantiating or the attribute is
  78. excluded using ``init=False``.
  79. If the value is an instance of `Factory`, its callable will be
  80. used to construct a new value (useful for mutable data types like lists
  81. or dicts).
  82. If a default is not set (or set manually to ``attr.NOTHING``), a value
  83. *must* be supplied when instantiating; otherwise a `TypeError`
  84. will be raised.
  85. The default can also be set using decorator notation as shown below.
  86. :type default: Any value
  87. :param callable factory: Syntactic sugar for
  88. ``default=attr.Factory(callable)``.
  89. :param validator: `callable` that is called by ``attrs``-generated
  90. ``__init__`` methods after the instance has been initialized. They
  91. receive the initialized instance, the `Attribute`, and the
  92. passed value.
  93. The return value is *not* inspected so the validator has to throw an
  94. exception itself.
  95. If a ``list`` is passed, its items are treated as validators and must
  96. all pass.
  97. Validators can be globally disabled and re-enabled using
  98. `get_run_validators`.
  99. The validator can also be set using decorator notation as shown below.
  100. :type validator: ``callable`` or a ``list`` of ``callable``\\ s.
  101. :param repr: Include this attribute in the generated ``__repr__``
  102. method. If ``True``, include the attribute; if ``False``, omit it. By
  103. default, the built-in ``repr()`` function is used. To override how the
  104. attribute value is formatted, pass a ``callable`` that takes a single
  105. value and returns a string. Note that the resulting string is used
  106. as-is, i.e. it will be used directly *instead* of calling ``repr()``
  107. (the default).
  108. :type repr: a ``bool`` or a ``callable`` to use a custom function.
  109. :param bool eq: If ``True`` (default), include this attribute in the
  110. generated ``__eq__`` and ``__ne__`` methods that check two instances
  111. for equality.
  112. :param bool order: If ``True`` (default), include this attributes in the
  113. generated ``__lt__``, ``__le__``, ``__gt__`` and ``__ge__`` methods.
  114. :param bool cmp: Setting to ``True`` is equivalent to setting ``eq=True,
  115. order=True``. Deprecated in favor of *eq* and *order*.
  116. :param hash: Include this attribute in the generated ``__hash__``
  117. method. If ``None`` (default), mirror *eq*'s value. This is the
  118. correct behavior according the Python spec. Setting this value to
  119. anything else than ``None`` is *discouraged*.
  120. :type hash: ``bool`` or ``None``
  121. :param bool init: Include this attribute in the generated ``__init__``
  122. method. It is possible to set this to ``False`` and set a default
  123. value. In that case this attributed is unconditionally initialized
  124. with the specified default value or factory.
  125. :param callable converter: `callable` that is called by
  126. ``attrs``-generated ``__init__`` methods to converter attribute's value
  127. to the desired format. It is given the passed-in value, and the
  128. returned value will be used as the new value of the attribute. The
  129. value is converted before being passed to the validator, if any.
  130. :param metadata: An arbitrary mapping, to be used by third-party
  131. components. See `extending_metadata`.
  132. :param type: The type of the attribute. In Python 3.6 or greater, the
  133. preferred method to specify the type is using a variable annotation
  134. (see `PEP 526 <https://www.python.org/dev/peps/pep-0526/>`_).
  135. This argument is provided for backward compatibility.
  136. Regardless of the approach used, the type will be stored on
  137. ``Attribute.type``.
  138. Please note that ``attrs`` doesn't do anything with this metadata by
  139. itself. You can use it as part of your own code or for
  140. `static type checking <types>`.
  141. :param kw_only: Make this attribute keyword-only (Python 3+)
  142. in the generated ``__init__`` (if ``init`` is ``False``, this
  143. parameter is ignored).
  144. .. versionadded:: 15.2.0 *convert*
  145. .. versionadded:: 16.3.0 *metadata*
  146. .. versionchanged:: 17.1.0 *validator* can be a ``list`` now.
  147. .. versionchanged:: 17.1.0
  148. *hash* is ``None`` and therefore mirrors *eq* by default.
  149. .. versionadded:: 17.3.0 *type*
  150. .. deprecated:: 17.4.0 *convert*
  151. .. versionadded:: 17.4.0 *converter* as a replacement for the deprecated
  152. *convert* to achieve consistency with other noun-based arguments.
  153. .. versionadded:: 18.1.0
  154. ``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``.
  155. .. versionadded:: 18.2.0 *kw_only*
  156. .. versionchanged:: 19.2.0 *convert* keyword argument removed
  157. .. versionchanged:: 19.2.0 *repr* also accepts a custom callable.
  158. .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01.
  159. .. versionadded:: 19.2.0 *eq* and *order*
  160. """
  161. eq, order = _determine_eq_order(cmp, eq, order)
  162. if hash is not None and hash is not True and hash is not False:
  163. raise TypeError(
  164. "Invalid value for hash. Must be True, False, or None."
  165. )
  166. if factory is not None:
  167. if default is not NOTHING:
  168. raise ValueError(
  169. "The `default` and `factory` arguments are mutually "
  170. "exclusive."
  171. )
  172. if not callable(factory):
  173. raise ValueError("The `factory` argument must be a callable.")
  174. default = Factory(factory)
  175. if metadata is None:
  176. metadata = {}
  177. return _CountingAttr(
  178. default=default,
  179. validator=validator,
  180. repr=repr,
  181. cmp=None,
  182. hash=hash,
  183. init=init,
  184. converter=converter,
  185. metadata=metadata,
  186. type=type,
  187. kw_only=kw_only,
  188. eq=eq,
  189. order=order,
  190. )
  191. def _make_attr_tuple_class(cls_name, attr_names):
  192. """
  193. Create a tuple subclass to hold `Attribute`s for an `attrs` class.
  194. The subclass is a bare tuple with properties for names.
  195. class MyClassAttributes(tuple):
  196. __slots__ = ()
  197. x = property(itemgetter(0))
  198. """
  199. attr_class_name = "{}Attributes".format(cls_name)
  200. attr_class_template = [
  201. "class {}(tuple):".format(attr_class_name),
  202. " __slots__ = ()",
  203. ]
  204. if attr_names:
  205. for i, attr_name in enumerate(attr_names):
  206. attr_class_template.append(
  207. _tuple_property_pat.format(index=i, attr_name=attr_name)
  208. )
  209. else:
  210. attr_class_template.append(" pass")
  211. globs = {"_attrs_itemgetter": itemgetter, "_attrs_property": property}
  212. eval(compile("\n".join(attr_class_template), "", "exec"), globs)
  213. return globs[attr_class_name]
  214. # Tuple class for extracted attributes from a class definition.
  215. # `base_attrs` is a subset of `attrs`.
  216. _Attributes = _make_attr_tuple_class(
  217. "_Attributes",
  218. [
  219. # all attributes to build dunder methods for
  220. "attrs",
  221. # attributes that have been inherited
  222. "base_attrs",
  223. # map inherited attributes to their originating classes
  224. "base_attrs_map",
  225. ],
  226. )
  227. def _is_class_var(annot):
  228. """
  229. Check whether *annot* is a typing.ClassVar.
  230. The string comparison hack is used to avoid evaluating all string
  231. annotations which would put attrs-based classes at a performance
  232. disadvantage compared to plain old classes.
  233. """
  234. return str(annot).startswith(_classvar_prefixes)
  235. def _get_annotations(cls):
  236. """
  237. Get annotations for *cls*.
  238. """
  239. anns = getattr(cls, "__annotations__", None)
  240. if anns is None:
  241. return {}
  242. # Verify that the annotations aren't merely inherited.
  243. for base_cls in cls.__mro__[1:]:
  244. if anns is getattr(base_cls, "__annotations__", None):
  245. return {}
  246. return anns
  247. def _counter_getter(e):
  248. """
  249. Key function for sorting to avoid re-creating a lambda for every class.
  250. """
  251. return e[1].counter
  252. def _transform_attrs(cls, these, auto_attribs, kw_only):
  253. """
  254. Transform all `_CountingAttr`s on a class into `Attribute`s.
  255. If *these* is passed, use that and don't look for them on the class.
  256. Return an `_Attributes`.
  257. """
  258. cd = cls.__dict__
  259. anns = _get_annotations(cls)
  260. if these is not None:
  261. ca_list = [(name, ca) for name, ca in iteritems(these)]
  262. if not isinstance(these, ordered_dict):
  263. ca_list.sort(key=_counter_getter)
  264. elif auto_attribs is True:
  265. ca_names = {
  266. name
  267. for name, attr in cd.items()
  268. if isinstance(attr, _CountingAttr)
  269. }
  270. ca_list = []
  271. annot_names = set()
  272. for attr_name, type in anns.items():
  273. if _is_class_var(type):
  274. continue
  275. annot_names.add(attr_name)
  276. a = cd.get(attr_name, NOTHING)
  277. if not isinstance(a, _CountingAttr):
  278. if a is NOTHING:
  279. a = attrib()
  280. else:
  281. a = attrib(default=a)
  282. ca_list.append((attr_name, a))
  283. unannotated = ca_names - annot_names
  284. if len(unannotated) > 0:
  285. raise UnannotatedAttributeError(
  286. "The following `attr.ib`s lack a type annotation: "
  287. + ", ".join(
  288. sorted(unannotated, key=lambda n: cd.get(n).counter)
  289. )
  290. + "."
  291. )
  292. else:
  293. ca_list = sorted(
  294. (
  295. (name, attr)
  296. for name, attr in cd.items()
  297. if isinstance(attr, _CountingAttr)
  298. ),
  299. key=lambda e: e[1].counter,
  300. )
  301. own_attrs = [
  302. Attribute.from_counting_attr(
  303. name=attr_name, ca=ca, type=anns.get(attr_name)
  304. )
  305. for attr_name, ca in ca_list
  306. ]
  307. base_attrs = []
  308. base_attr_map = {} # A dictionary of base attrs to their classes.
  309. taken_attr_names = {a.name: a for a in own_attrs}
  310. # Traverse the MRO and collect attributes.
  311. for base_cls in cls.__mro__[1:-1]:
  312. sub_attrs = getattr(base_cls, "__attrs_attrs__", None)
  313. if sub_attrs is not None:
  314. for a in sub_attrs:
  315. prev_a = taken_attr_names.get(a.name)
  316. # Only add an attribute if it hasn't been defined before. This
  317. # allows for overwriting attribute definitions by subclassing.
  318. if prev_a is None:
  319. base_attrs.append(a)
  320. taken_attr_names[a.name] = a
  321. base_attr_map[a.name] = base_cls
  322. attr_names = [a.name for a in base_attrs + own_attrs]
  323. AttrsClass = _make_attr_tuple_class(cls.__name__, attr_names)
  324. if kw_only:
  325. own_attrs = [a._assoc(kw_only=True) for a in own_attrs]
  326. base_attrs = [a._assoc(kw_only=True) for a in base_attrs]
  327. attrs = AttrsClass(base_attrs + own_attrs)
  328. # Mandatory vs non-mandatory attr order only matters when they are part of
  329. # the __init__ signature and when they aren't kw_only (which are moved to
  330. # the end and can be mandatory or non-mandatory in any order, as they will
  331. # be specified as keyword args anyway). Check the order of those attrs:
  332. had_default = False
  333. for a in (a for a in attrs if a.init is not False and a.kw_only is False):
  334. if had_default is True and a.default is NOTHING:
  335. raise ValueError(
  336. "No mandatory attributes allowed after an attribute with a "
  337. "default value or factory. Attribute in question: %r" % (a,)
  338. )
  339. if had_default is False and a.default is not NOTHING:
  340. had_default = True
  341. return _Attributes((attrs, base_attrs, base_attr_map))
  342. def _frozen_setattrs(self, name, value):
  343. """
  344. Attached to frozen classes as __setattr__.
  345. """
  346. raise FrozenInstanceError()
  347. def _frozen_delattrs(self, name):
  348. """
  349. Attached to frozen classes as __delattr__.
  350. """
  351. raise FrozenInstanceError()
  352. class _ClassBuilder(object):
  353. """
  354. Iteratively build *one* class.
  355. """
  356. __slots__ = (
  357. "_cls",
  358. "_cls_dict",
  359. "_attrs",
  360. "_base_names",
  361. "_attr_names",
  362. "_slots",
  363. "_frozen",
  364. "_weakref_slot",
  365. "_cache_hash",
  366. "_has_post_init",
  367. "_delete_attribs",
  368. "_base_attr_map",
  369. "_is_exc",
  370. )
  371. def __init__(
  372. self,
  373. cls,
  374. these,
  375. slots,
  376. frozen,
  377. weakref_slot,
  378. auto_attribs,
  379. kw_only,
  380. cache_hash,
  381. is_exc,
  382. ):
  383. attrs, base_attrs, base_map = _transform_attrs(
  384. cls, these, auto_attribs, kw_only
  385. )
  386. self._cls = cls
  387. self._cls_dict = dict(cls.__dict__) if slots else {}
  388. self._attrs = attrs
  389. self._base_names = set(a.name for a in base_attrs)
  390. self._base_attr_map = base_map
  391. self._attr_names = tuple(a.name for a in attrs)
  392. self._slots = slots
  393. self._frozen = frozen or _has_frozen_base_class(cls)
  394. self._weakref_slot = weakref_slot
  395. self._cache_hash = cache_hash
  396. self._has_post_init = bool(getattr(cls, "__attrs_post_init__", False))
  397. self._delete_attribs = not bool(these)
  398. self._is_exc = is_exc
  399. self._cls_dict["__attrs_attrs__"] = self._attrs
  400. if frozen:
  401. self._cls_dict["__setattr__"] = _frozen_setattrs
  402. self._cls_dict["__delattr__"] = _frozen_delattrs
  403. def __repr__(self):
  404. return "<_ClassBuilder(cls={cls})>".format(cls=self._cls.__name__)
  405. def build_class(self):
  406. """
  407. Finalize class based on the accumulated configuration.
  408. Builder cannot be used after calling this method.
  409. """
  410. if self._slots is True:
  411. return self._create_slots_class()
  412. else:
  413. return self._patch_original_class()
  414. def _patch_original_class(self):
  415. """
  416. Apply accumulated methods and return the class.
  417. """
  418. cls = self._cls
  419. base_names = self._base_names
  420. # Clean class of attribute definitions (`attr.ib()`s).
  421. if self._delete_attribs:
  422. for name in self._attr_names:
  423. if (
  424. name not in base_names
  425. and getattr(cls, name, _sentinel) is not _sentinel
  426. ):
  427. try:
  428. delattr(cls, name)
  429. except AttributeError:
  430. # This can happen if a base class defines a class
  431. # variable and we want to set an attribute with the
  432. # same name by using only a type annotation.
  433. pass
  434. # Attach our dunder methods.
  435. for name, value in self._cls_dict.items():
  436. setattr(cls, name, value)
  437. # Attach __setstate__. This is necessary to clear the hash code
  438. # cache on deserialization. See issue
  439. # https://github.com/python-attrs/attrs/issues/482 .
  440. # Note that this code only handles setstate for dict classes.
  441. # For slotted classes, see similar code in _create_slots_class .
  442. if self._cache_hash:
  443. existing_set_state_method = getattr(cls, "__setstate__", None)
  444. if existing_set_state_method:
  445. raise NotImplementedError(
  446. "Currently you cannot use hash caching if "
  447. "you specify your own __setstate__ method."
  448. "See https://github.com/python-attrs/attrs/issues/494 ."
  449. )
  450. def cache_hash_set_state(chss_self, _):
  451. # clear hash code cache
  452. setattr(chss_self, _hash_cache_field, None)
  453. setattr(cls, "__setstate__", cache_hash_set_state)
  454. return cls
  455. def _create_slots_class(self):
  456. """
  457. Build and return a new class with a `__slots__` attribute.
  458. """
  459. base_names = self._base_names
  460. cd = {
  461. k: v
  462. for k, v in iteritems(self._cls_dict)
  463. if k not in tuple(self._attr_names) + ("__dict__", "__weakref__")
  464. }
  465. weakref_inherited = False
  466. # Traverse the MRO to check for an existing __weakref__.
  467. for base_cls in self._cls.__mro__[1:-1]:
  468. if "__weakref__" in getattr(base_cls, "__dict__", ()):
  469. weakref_inherited = True
  470. break
  471. names = self._attr_names
  472. if (
  473. self._weakref_slot
  474. and "__weakref__" not in getattr(self._cls, "__slots__", ())
  475. and "__weakref__" not in names
  476. and not weakref_inherited
  477. ):
  478. names += ("__weakref__",)
  479. # We only add the names of attributes that aren't inherited.
  480. # Settings __slots__ to inherited attributes wastes memory.
  481. slot_names = [name for name in names if name not in base_names]
  482. if self._cache_hash:
  483. slot_names.append(_hash_cache_field)
  484. cd["__slots__"] = tuple(slot_names)
  485. qualname = getattr(self._cls, "__qualname__", None)
  486. if qualname is not None:
  487. cd["__qualname__"] = qualname
  488. # __weakref__ is not writable.
  489. state_attr_names = tuple(
  490. an for an in self._attr_names if an != "__weakref__"
  491. )
  492. def slots_getstate(self):
  493. """
  494. Automatically created by attrs.
  495. """
  496. return tuple(getattr(self, name) for name in state_attr_names)
  497. hash_caching_enabled = self._cache_hash
  498. def slots_setstate(self, state):
  499. """
  500. Automatically created by attrs.
  501. """
  502. __bound_setattr = _obj_setattr.__get__(self, Attribute)
  503. for name, value in zip(state_attr_names, state):
  504. __bound_setattr(name, value)
  505. # Clearing the hash code cache on deserialization is needed
  506. # because hash codes can change from run to run. See issue
  507. # https://github.com/python-attrs/attrs/issues/482 .
  508. # Note that this code only handles setstate for slotted classes.
  509. # For dict classes, see similar code in _patch_original_class .
  510. if hash_caching_enabled:
  511. __bound_setattr(_hash_cache_field, None)
  512. # slots and frozen require __getstate__/__setstate__ to work
  513. cd["__getstate__"] = slots_getstate
  514. cd["__setstate__"] = slots_setstate
  515. # Create new class based on old class and our methods.
  516. cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd)
  517. # The following is a fix for
  518. # https://github.com/python-attrs/attrs/issues/102. On Python 3,
  519. # if a method mentions `__class__` or uses the no-arg super(), the
  520. # compiler will bake a reference to the class in the method itself
  521. # as `method.__closure__`. Since we replace the class with a
  522. # clone, we rewrite these references so it keeps working.
  523. for item in cls.__dict__.values():
  524. if isinstance(item, (classmethod, staticmethod)):
  525. # Class- and staticmethods hide their functions inside.
  526. # These might need to be rewritten as well.
  527. closure_cells = getattr(item.__func__, "__closure__", None)
  528. else:
  529. closure_cells = getattr(item, "__closure__", None)
  530. if not closure_cells: # Catch None or the empty list.
  531. continue
  532. for cell in closure_cells:
  533. if cell.cell_contents is self._cls:
  534. set_closure_cell(cell, cls)
  535. return cls
  536. def add_repr(self, ns):
  537. self._cls_dict["__repr__"] = self._add_method_dunders(
  538. _make_repr(self._attrs, ns=ns)
  539. )
  540. return self
  541. def add_str(self):
  542. repr = self._cls_dict.get("__repr__")
  543. if repr is None:
  544. raise ValueError(
  545. "__str__ can only be generated if a __repr__ exists."
  546. )
  547. def __str__(self):
  548. return self.__repr__()
  549. self._cls_dict["__str__"] = self._add_method_dunders(__str__)
  550. return self
  551. def make_unhashable(self):
  552. self._cls_dict["__hash__"] = None
  553. return self
  554. def add_hash(self):
  555. self._cls_dict["__hash__"] = self._add_method_dunders(
  556. _make_hash(
  557. self._cls,
  558. self._attrs,
  559. frozen=self._frozen,
  560. cache_hash=self._cache_hash,
  561. )
  562. )
  563. return self
  564. def add_init(self):
  565. self._cls_dict["__init__"] = self._add_method_dunders(
  566. _make_init(
  567. self._cls,
  568. self._attrs,
  569. self._has_post_init,
  570. self._frozen,
  571. self._slots,
  572. self._cache_hash,
  573. self._base_attr_map,
  574. self._is_exc,
  575. )
  576. )
  577. return self
  578. def add_eq(self):
  579. cd = self._cls_dict
  580. cd["__eq__"], cd["__ne__"] = (
  581. self._add_method_dunders(meth)
  582. for meth in _make_eq(self._cls, self._attrs)
  583. )
  584. return self
  585. def add_order(self):
  586. cd = self._cls_dict
  587. cd["__lt__"], cd["__le__"], cd["__gt__"], cd["__ge__"] = (
  588. self._add_method_dunders(meth)
  589. for meth in _make_order(self._cls, self._attrs)
  590. )
  591. return self
  592. def _add_method_dunders(self, method):
  593. """
  594. Add __module__ and __qualname__ to a *method* if possible.
  595. """
  596. try:
  597. method.__module__ = self._cls.__module__
  598. except AttributeError:
  599. pass
  600. try:
  601. method.__qualname__ = ".".join(
  602. (self._cls.__qualname__, method.__name__)
  603. )
  604. except AttributeError:
  605. pass
  606. return method
  607. _CMP_DEPRECATION = (
  608. "The usage of `cmp` is deprecated and will be removed on or after "
  609. "2021-06-01. Please use `eq` and `order` instead."
  610. )
  611. def _determine_eq_order(cmp, eq, order):
  612. """
  613. Validate the combination of *cmp*, *eq*, and *order*. Derive the effective
  614. values of eq and order.
  615. """
  616. if cmp is not None and any((eq is not None, order is not None)):
  617. raise ValueError("Don't mix `cmp` with `eq' and `order`.")
  618. # cmp takes precedence due to bw-compatibility.
  619. if cmp is not None:
  620. warnings.warn(_CMP_DEPRECATION, DeprecationWarning, stacklevel=3)
  621. return cmp, cmp
  622. # If left None, equality is on and ordering mirrors equality.
  623. if eq is None:
  624. eq = True
  625. if order is None:
  626. order = eq
  627. if eq is False and order is True:
  628. raise ValueError("`order` can only be True if `eq` is True too.")
  629. return eq, order
  630. def attrs(
  631. maybe_cls=None,
  632. these=None,
  633. repr_ns=None,
  634. repr=True,
  635. cmp=None,
  636. hash=None,
  637. init=True,
  638. slots=False,
  639. frozen=False,
  640. weakref_slot=True,
  641. str=False,
  642. auto_attribs=False,
  643. kw_only=False,
  644. cache_hash=False,
  645. auto_exc=False,
  646. eq=None,
  647. order=None,
  648. ):
  649. r"""
  650. A class decorator that adds `dunder
  651. <https://wiki.python.org/moin/DunderAlias>`_\ -methods according to the
  652. specified attributes using `attr.ib` or the *these* argument.
  653. :param these: A dictionary of name to `attr.ib` mappings. This is
  654. useful to avoid the definition of your attributes within the class body
  655. because you can't (e.g. if you want to add ``__repr__`` methods to
  656. Django models) or don't want to.
  657. If *these* is not ``None``, ``attrs`` will *not* search the class body
  658. for attributes and will *not* remove any attributes from it.
  659. If *these* is an ordered dict (`dict` on Python 3.6+,
  660. `collections.OrderedDict` otherwise), the order is deduced from
  661. the order of the attributes inside *these*. Otherwise the order
  662. of the definition of the attributes is used.
  663. :type these: `dict` of `str` to `attr.ib`
  664. :param str repr_ns: When using nested classes, there's no way in Python 2
  665. to automatically detect that. Therefore it's possible to set the
  666. namespace explicitly for a more meaningful ``repr`` output.
  667. :param bool repr: Create a ``__repr__`` method with a human readable
  668. representation of ``attrs`` attributes..
  669. :param bool str: Create a ``__str__`` method that is identical to
  670. ``__repr__``. This is usually not necessary except for
  671. `Exception`\ s.
  672. :param bool eq: If ``True`` or ``None`` (default), add ``__eq__`` and
  673. ``__ne__`` methods that check two instances for equality.
  674. They compare the instances as if they were tuples of their ``attrs``
  675. attributes, but only iff the types of both classes are *identical*!
  676. :type eq: `bool` or `None`
  677. :param bool order: If ``True``, add ``__lt__``, ``__le__``, ``__gt__``,
  678. and ``__ge__`` methods that behave like *eq* above and allow instances
  679. to be ordered. If ``None`` (default) mirror value of *eq*.
  680. :type order: `bool` or `None`
  681. :param cmp: Setting to ``True`` is equivalent to setting ``eq=True,
  682. order=True``. Deprecated in favor of *eq* and *order*, has precedence
  683. over them for backward-compatibility though. Must not be mixed with
  684. *eq* or *order*.
  685. :type cmp: `bool` or `None`
  686. :param hash: If ``None`` (default), the ``__hash__`` method is generated
  687. according how *eq* and *frozen* are set.
  688. 1. If *both* are True, ``attrs`` will generate a ``__hash__`` for you.
  689. 2. If *eq* is True and *frozen* is False, ``__hash__`` will be set to
  690. None, marking it unhashable (which it is).
  691. 3. If *eq* is False, ``__hash__`` will be left untouched meaning the
  692. ``__hash__`` method of the base class will be used (if base class is
  693. ``object``, this means it will fall back to id-based hashing.).
  694. Although not recommended, you can decide for yourself and force
  695. ``attrs`` to create one (e.g. if the class is immutable even though you
  696. didn't freeze it programmatically) by passing ``True`` or not. Both of
  697. these cases are rather special and should be used carefully.
  698. See our documentation on `hashing`, Python's documentation on
  699. `object.__hash__`, and the `GitHub issue that led to the default \
  700. behavior <https://github.com/python-attrs/attrs/issues/136>`_ for more
  701. details.
  702. :type hash: ``bool`` or ``None``
  703. :param bool init: Create a ``__init__`` method that initializes the
  704. ``attrs`` attributes. Leading underscores are stripped for the
  705. argument name. If a ``__attrs_post_init__`` method exists on the
  706. class, it will be called after the class is fully initialized.
  707. :param bool slots: Create a `slotted class <slotted classes>` that's more
  708. memory-efficient.
  709. :param bool frozen: Make instances immutable after initialization. If
  710. someone attempts to modify a frozen instance,
  711. `attr.exceptions.FrozenInstanceError` is raised.
  712. Please note:
  713. 1. This is achieved by installing a custom ``__setattr__`` method
  714. on your class, so you can't implement your own.
  715. 2. True immutability is impossible in Python.
  716. 3. This *does* have a minor a runtime performance `impact
  717. <how-frozen>` when initializing new instances. In other words:
  718. ``__init__`` is slightly slower with ``frozen=True``.
  719. 4. If a class is frozen, you cannot modify ``self`` in
  720. ``__attrs_post_init__`` or a self-written ``__init__``. You can
  721. circumvent that limitation by using
  722. ``object.__setattr__(self, "attribute_name", value)``.
  723. :param bool weakref_slot: Make instances weak-referenceable. This has no
  724. effect unless ``slots`` is also enabled.
  725. :param bool auto_attribs: If True, collect `PEP 526`_-annotated attributes
  726. (Python 3.6 and later only) from the class body.
  727. In this case, you **must** annotate every field. If ``attrs``
  728. encounters a field that is set to an `attr.ib` but lacks a type
  729. annotation, an `attr.exceptions.UnannotatedAttributeError` is
  730. raised. Use ``field_name: typing.Any = attr.ib(...)`` if you don't
  731. want to set a type.
  732. If you assign a value to those attributes (e.g. ``x: int = 42``), that
  733. value becomes the default value like if it were passed using
  734. ``attr.ib(default=42)``. Passing an instance of `Factory` also
  735. works as expected.
  736. Attributes annotated as `typing.ClassVar`, and attributes that are
  737. neither annotated nor set to an `attr.ib` are **ignored**.
  738. .. _`PEP 526`: https://www.python.org/dev/peps/pep-0526/
  739. :param bool kw_only: Make all attributes keyword-only (Python 3+)
  740. in the generated ``__init__`` (if ``init`` is ``False``, this
  741. parameter is ignored).
  742. :param bool cache_hash: Ensure that the object's hash code is computed
  743. only once and stored on the object. If this is set to ``True``,
  744. hashing must be either explicitly or implicitly enabled for this
  745. class. If the hash code is cached, avoid any reassignments of
  746. fields involved in hash code computation or mutations of the objects
  747. those fields point to after object creation. If such changes occur,
  748. the behavior of the object's hash code is undefined.
  749. :param bool auto_exc: If the class subclasses `BaseException`
  750. (which implicitly includes any subclass of any exception), the
  751. following happens to behave like a well-behaved Python exceptions
  752. class:
  753. - the values for *eq*, *order*, and *hash* are ignored and the
  754. instances compare and hash by the instance's ids (N.B. ``attrs`` will
  755. *not* remove existing implementations of ``__hash__`` or the equality
  756. methods. It just won't add own ones.),
  757. - all attributes that are either passed into ``__init__`` or have a
  758. default value are additionally available as a tuple in the ``args``
  759. attribute,
  760. - the value of *str* is ignored leaving ``__str__`` to base classes.
  761. .. versionadded:: 16.0.0 *slots*
  762. .. versionadded:: 16.1.0 *frozen*
  763. .. versionadded:: 16.3.0 *str*
  764. .. versionadded:: 16.3.0 Support for ``__attrs_post_init__``.
  765. .. versionchanged:: 17.1.0
  766. *hash* supports ``None`` as value which is also the default now.
  767. .. versionadded:: 17.3.0 *auto_attribs*
  768. .. versionchanged:: 18.1.0
  769. If *these* is passed, no attributes are deleted from the class body.
  770. .. versionchanged:: 18.1.0 If *these* is ordered, the order is retained.
  771. .. versionadded:: 18.2.0 *weakref_slot*
  772. .. deprecated:: 18.2.0
  773. ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now raise a
  774. `DeprecationWarning` if the classes compared are subclasses of
  775. each other. ``__eq`` and ``__ne__`` never tried to compared subclasses
  776. to each other.
  777. .. versionchanged:: 19.2.0
  778. ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now do not consider
  779. subclasses comparable anymore.
  780. .. versionadded:: 18.2.0 *kw_only*
  781. .. versionadded:: 18.2.0 *cache_hash*
  782. .. versionadded:: 19.1.0 *auto_exc*
  783. .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01.
  784. .. versionadded:: 19.2.0 *eq* and *order*
  785. """
  786. eq, order = _determine_eq_order(cmp, eq, order)
  787. def wrap(cls):
  788. if getattr(cls, "__class__", None) is None:
  789. raise TypeError("attrs only works with new-style classes.")
  790. is_exc = auto_exc is True and issubclass(cls, BaseException)
  791. builder = _ClassBuilder(
  792. cls,
  793. these,
  794. slots,
  795. frozen,
  796. weakref_slot,
  797. auto_attribs,
  798. kw_only,
  799. cache_hash,
  800. is_exc,
  801. )
  802. if repr is True:
  803. builder.add_repr(repr_ns)
  804. if str is True:
  805. builder.add_str()
  806. if eq is True and not is_exc:
  807. builder.add_eq()
  808. if order is True and not is_exc:
  809. builder.add_order()
  810. if hash is not True and hash is not False and hash is not None:
  811. # Can't use `hash in` because 1 == True for example.
  812. raise TypeError(
  813. "Invalid value for hash. Must be True, False, or None."
  814. )
  815. elif hash is False or (hash is None and eq is False) or is_exc:
  816. # Don't do anything. Should fall back to __object__'s __hash__
  817. # which is by id.
  818. if cache_hash:
  819. raise TypeError(
  820. "Invalid value for cache_hash. To use hash caching,"
  821. " hashing must be either explicitly or implicitly "
  822. "enabled."
  823. )
  824. elif hash is True or (hash is None and eq is True and frozen is True):
  825. # Build a __hash__ if told so, or if it's safe.
  826. builder.add_hash()
  827. else:
  828. # Raise TypeError on attempts to hash.
  829. if cache_hash:
  830. raise TypeError(
  831. "Invalid value for cache_hash. To use hash caching,"
  832. " hashing must be either explicitly or implicitly "
  833. "enabled."
  834. )
  835. builder.make_unhashable()
  836. if init is True:
  837. builder.add_init()
  838. else:
  839. if cache_hash:
  840. raise TypeError(
  841. "Invalid value for cache_hash. To use hash caching,"
  842. " init must be True."
  843. )
  844. return builder.build_class()
  845. # maybe_cls's type depends on the usage of the decorator. It's a class
  846. # if it's used as `@attrs` but ``None`` if used as `@attrs()`.
  847. if maybe_cls is None:
  848. return wrap
  849. else:
  850. return wrap(maybe_cls)
  851. _attrs = attrs
  852. """
  853. Internal alias so we can use it in functions that take an argument called
  854. *attrs*.
  855. """
  856. if PY2:
  857. def _has_frozen_base_class(cls):
  858. """
  859. Check whether *cls* has a frozen ancestor by looking at its
  860. __setattr__.
  861. """
  862. return (
  863. getattr(cls.__setattr__, "__module__", None)
  864. == _frozen_setattrs.__module__
  865. and cls.__setattr__.__name__ == _frozen_setattrs.__name__
  866. )
  867. else:
  868. def _has_frozen_base_class(cls):
  869. """
  870. Check whether *cls* has a frozen ancestor by looking at its
  871. __setattr__.
  872. """
  873. return cls.__setattr__ == _frozen_setattrs
  874. def _attrs_to_tuple(obj, attrs):
  875. """
  876. Create a tuple of all values of *obj*'s *attrs*.
  877. """
  878. return tuple(getattr(obj, a.name) for a in attrs)
  879. def _generate_unique_filename(cls, func_name):
  880. """
  881. Create a "filename" suitable for a function being generated.
  882. """
  883. unique_id = uuid.uuid4()
  884. extra = ""
  885. count = 1
  886. while True:
  887. unique_filename = "<attrs generated {0} {1}.{2}{3}>".format(
  888. func_name,
  889. cls.__module__,
  890. getattr(cls, "__qualname__", cls.__name__),
  891. extra,
  892. )
  893. # To handle concurrency we essentially "reserve" our spot in
  894. # the linecache with a dummy line. The caller can then
  895. # set this value correctly.
  896. cache_line = (1, None, (str(unique_id),), unique_filename)
  897. if (
  898. linecache.cache.setdefault(unique_filename, cache_line)
  899. == cache_line
  900. ):
  901. return unique_filename
  902. # Looks like this spot is taken. Try again.
  903. count += 1
  904. extra = "-{0}".format(count)
  905. def _make_hash(cls, attrs, frozen, cache_hash):
  906. attrs = tuple(
  907. a for a in attrs if a.hash is True or (a.hash is None and a.eq is True)
  908. )
  909. tab = " "
  910. unique_filename = _generate_unique_filename(cls, "hash")
  911. type_hash = hash(unique_filename)
  912. method_lines = ["def __hash__(self):"]
  913. def append_hash_computation_lines(prefix, indent):
  914. """
  915. Generate the code for actually computing the hash code.
  916. Below this will either be returned directly or used to compute
  917. a value which is then cached, depending on the value of cache_hash
  918. """
  919. method_lines.extend(
  920. [indent + prefix + "hash((", indent + " %d," % (type_hash,)]
  921. )
  922. for a in attrs:
  923. method_lines.append(indent + " self.%s," % a.name)
  924. method_lines.append(indent + " ))")
  925. if cache_hash:
  926. method_lines.append(tab + "if self.%s is None:" % _hash_cache_field)
  927. if frozen:
  928. append_hash_computation_lines(
  929. "object.__setattr__(self, '%s', " % _hash_cache_field, tab * 2
  930. )
  931. method_lines.append(tab * 2 + ")") # close __setattr__
  932. else:
  933. append_hash_computation_lines(
  934. "self.%s = " % _hash_cache_field, tab * 2
  935. )
  936. method_lines.append(tab + "return self.%s" % _hash_cache_field)
  937. else:
  938. append_hash_computation_lines("return ", tab)
  939. script = "\n".join(method_lines)
  940. globs = {}
  941. locs = {}
  942. bytecode = compile(script, unique_filename, "exec")
  943. eval(bytecode, globs, locs)
  944. # In order of debuggers like PDB being able to step through the code,
  945. # we add a fake linecache entry.
  946. linecache.cache[unique_filename] = (
  947. len(script),
  948. None,
  949. script.splitlines(True),
  950. unique_filename,
  951. )
  952. return locs["__hash__"]
  953. def _add_hash(cls, attrs):
  954. """
  955. Add a hash method to *cls*.
  956. """
  957. cls.__hash__ = _make_hash(cls, attrs, frozen=False, cache_hash=False)
  958. return cls
  959. def __ne__(self, other):
  960. """
  961. Check equality and either forward a NotImplemented or return the result
  962. negated.
  963. """
  964. result = self.__eq__(other)
  965. if result is NotImplemented:
  966. return NotImplemented
  967. return not result
  968. def _make_eq(cls, attrs):
  969. attrs = [a for a in attrs if a.eq]
  970. unique_filename = _generate_unique_filename(cls, "eq")
  971. lines = [
  972. "def __eq__(self, other):",
  973. " if other.__class__ is not self.__class__:",
  974. " return NotImplemented",
  975. ]
  976. # We can't just do a big self.x = other.x and... clause due to
  977. # irregularities like nan == nan is false but (nan,) == (nan,) is true.
  978. if attrs:
  979. lines.append(" return (")
  980. others = [" ) == ("]
  981. for a in attrs:
  982. lines.append(" self.%s," % (a.name,))
  983. others.append(" other.%s," % (a.name,))
  984. lines += others + [" )"]
  985. else:
  986. lines.append(" return True")
  987. script = "\n".join(lines)
  988. globs = {}
  989. locs = {}
  990. bytecode = compile(script, unique_filename, "exec")
  991. eval(bytecode, globs, locs)
  992. # In order of debuggers like PDB being able to step through the code,
  993. # we add a fake linecache entry.
  994. linecache.cache[unique_filename] = (
  995. len(script),
  996. None,
  997. script.splitlines(True),
  998. unique_filename,
  999. )
  1000. return locs["__eq__"], __ne__
  1001. def _make_order(cls, attrs):
  1002. attrs = [a for a in attrs if a.order]
  1003. def attrs_to_tuple(obj):
  1004. """
  1005. Save us some typing.
  1006. """
  1007. return _attrs_to_tuple(obj, attrs)
  1008. def __lt__(self, other):
  1009. """
  1010. Automatically created by attrs.
  1011. """
  1012. if other.__class__ is self.__class__:
  1013. return attrs_to_tuple(self) < attrs_to_tuple(other)
  1014. return NotImplemented
  1015. def __le__(self, other):
  1016. """
  1017. Automatically created by attrs.
  1018. """
  1019. if other.__class__ is self.__class__:
  1020. return attrs_to_tuple(self) <= attrs_to_tuple(other)
  1021. return NotImplemented
  1022. def __gt__(self, other):
  1023. """
  1024. Automatically created by attrs.
  1025. """
  1026. if other.__class__ is self.__class__:
  1027. return attrs_to_tuple(self) > attrs_to_tuple(other)
  1028. return NotImplemented
  1029. def __ge__(self, other):
  1030. """
  1031. Automatically created by attrs.
  1032. """
  1033. if other.__class__ is self.__class__:
  1034. return attrs_to_tuple(self) >= attrs_to_tuple(other)
  1035. return NotImplemented
  1036. return __lt__, __le__, __gt__, __ge__
  1037. def _add_eq(cls, attrs=None):
  1038. """
  1039. Add equality methods to *cls* with *attrs*.
  1040. """
  1041. if attrs is None:
  1042. attrs = cls.__attrs_attrs__
  1043. cls.__eq__, cls.__ne__ = _make_eq(cls, attrs)
  1044. return cls
  1045. _already_repring = threading.local()
  1046. def _make_repr(attrs, ns):
  1047. """
  1048. Make a repr method that includes relevant *attrs*, adding *ns* to the full
  1049. name.
  1050. """
  1051. # Figure out which attributes to include, and which function to use to
  1052. # format them. The a.repr value can be either bool or a custom callable.
  1053. attr_names_with_reprs = tuple(
  1054. (a.name, repr if a.repr is True else a.repr)
  1055. for a in attrs
  1056. if a.repr is not False
  1057. )
  1058. def __repr__(self):
  1059. """
  1060. Automatically created by attrs.
  1061. """
  1062. try:
  1063. working_set = _already_repring.working_set
  1064. except AttributeError:
  1065. working_set = set()
  1066. _already_repring.working_set = working_set
  1067. if id(self) in working_set:
  1068. return "..."
  1069. real_cls = self.__class__
  1070. if ns is None:
  1071. qualname = getattr(real_cls, "__qualname__", None)
  1072. if qualname is not None:
  1073. class_name = qualname.rsplit(">.", 1)[-1]
  1074. else:
  1075. class_name = real_cls.__name__
  1076. else:
  1077. class_name = ns + "." + real_cls.__name__
  1078. # Since 'self' remains on the stack (i.e.: strongly referenced) for the
  1079. # duration of this call, it's safe to depend on id(...) stability, and
  1080. # not need to track the instance and therefore worry about properties
  1081. # like weakref- or hash-ability.
  1082. working_set.add(id(self))
  1083. try:
  1084. result = [class_name, "("]
  1085. first = True
  1086. for name, attr_repr in attr_names_with_reprs:
  1087. if first:
  1088. first = False
  1089. else:
  1090. result.append(", ")
  1091. result.extend(
  1092. (name, "=", attr_repr(getattr(self, name, NOTHING)))
  1093. )
  1094. return "".join(result) + ")"
  1095. finally:
  1096. working_set.remove(id(self))
  1097. return __repr__
  1098. def _add_repr(cls, ns=None, attrs=None):
  1099. """
  1100. Add a repr method to *cls*.
  1101. """
  1102. if attrs is None:
  1103. attrs = cls.__attrs_attrs__
  1104. cls.__repr__ = _make_repr(attrs, ns)
  1105. return cls
  1106. def _make_init(
  1107. cls, attrs, post_init, frozen, slots, cache_hash, base_attr_map, is_exc
  1108. ):
  1109. attrs = [a for a in attrs if a.init or a.default is not NOTHING]
  1110. unique_filename = _generate_unique_filename(cls, "init")
  1111. script, globs, annotations = _attrs_to_init_script(
  1112. attrs, frozen, slots, post_init, cache_hash, base_attr_map, is_exc
  1113. )
  1114. locs = {}
  1115. bytecode = compile(script, unique_filename, "exec")
  1116. attr_dict = dict((a.name, a) for a in attrs)
  1117. globs.update({"NOTHING": NOTHING, "attr_dict": attr_dict})
  1118. if frozen is True:
  1119. # Save the lookup overhead in __init__ if we need to circumvent
  1120. # immutability.
  1121. globs["_cached_setattr"] = _obj_setattr
  1122. eval(bytecode, globs, locs)
  1123. # In order of debuggers like PDB being able to step through the code,
  1124. # we add a fake linecache entry.
  1125. linecache.cache[unique_filename] = (
  1126. len(script),
  1127. None,
  1128. script.splitlines(True),
  1129. unique_filename,
  1130. )
  1131. __init__ = locs["__init__"]
  1132. __init__.__annotations__ = annotations
  1133. return __init__
  1134. def fields(cls):
  1135. """
  1136. Return the tuple of ``attrs`` attributes for a class.
  1137. The tuple also allows accessing the fields by their names (see below for
  1138. examples).
  1139. :param type cls: Class to introspect.
  1140. :raise TypeError: If *cls* is not a class.
  1141. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
  1142. class.
  1143. :rtype: tuple (with name accessors) of `attr.Attribute`
  1144. .. versionchanged:: 16.2.0 Returned tuple allows accessing the fields
  1145. by name.
  1146. """
  1147. if not isclass(cls):
  1148. raise TypeError("Passed object must be a class.")
  1149. attrs = getattr(cls, "__attrs_attrs__", None)
  1150. if attrs is None:
  1151. raise NotAnAttrsClassError(
  1152. "{cls!r} is not an attrs-decorated class.".format(cls=cls)
  1153. )
  1154. return attrs
  1155. def fields_dict(cls):
  1156. """
  1157. Return an ordered dictionary of ``attrs`` attributes for a class, whose
  1158. keys are the attribute names.
  1159. :param type cls: Class to introspect.
  1160. :raise TypeError: If *cls* is not a class.
  1161. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
  1162. class.
  1163. :rtype: an ordered dict where keys are attribute names and values are
  1164. `attr.Attribute`\\ s. This will be a `dict` if it's
  1165. naturally ordered like on Python 3.6+ or an
  1166. :class:`~collections.OrderedDict` otherwise.
  1167. .. versionadded:: 18.1.0
  1168. """
  1169. if not isclass(cls):
  1170. raise TypeError("Passed object must be a class.")
  1171. attrs = getattr(cls, "__attrs_attrs__", None)
  1172. if attrs is None:
  1173. raise NotAnAttrsClassError(
  1174. "{cls!r} is not an attrs-decorated class.".format(cls=cls)
  1175. )
  1176. return ordered_dict(((a.name, a) for a in attrs))
  1177. def validate(inst):
  1178. """
  1179. Validate all attributes on *inst* that have a validator.
  1180. Leaves all exceptions through.
  1181. :param inst: Instance of a class with ``attrs`` attributes.
  1182. """
  1183. if _config._run_validators is False:
  1184. return
  1185. for a in fields(inst.__class__):
  1186. v = a.validator
  1187. if v is not None:
  1188. v(inst, a, getattr(inst, a.name))
  1189. def _is_slot_cls(cls):
  1190. return "__slots__" in cls.__dict__
  1191. def _is_slot_attr(a_name, base_attr_map):
  1192. """
  1193. Check if the attribute name comes from a slot class.
  1194. """
  1195. return a_name in base_attr_map and _is_slot_cls(base_attr_map[a_name])
  1196. def _attrs_to_init_script(
  1197. attrs, frozen, slots, post_init, cache_hash, base_attr_map, is_exc
  1198. ):
  1199. """
  1200. Return a script of an initializer for *attrs* and a dict of globals.
  1201. The globals are expected by the generated script.
  1202. If *frozen* is True, we cannot set the attributes directly so we use
  1203. a cached ``object.__setattr__``.
  1204. """
  1205. lines = []
  1206. any_slot_ancestors = any(
  1207. _is_slot_attr(a.name, base_attr_map) for a in attrs
  1208. )
  1209. if frozen is True:
  1210. if slots is True:
  1211. lines.append(
  1212. # Circumvent the __setattr__ descriptor to save one lookup per
  1213. # assignment.
  1214. # Note _setattr will be used again below if cache_hash is True
  1215. "_setattr = _cached_setattr.__get__(self, self.__class__)"
  1216. )
  1217. def fmt_setter(attr_name, value_var):
  1218. return "_setattr('%(attr_name)s', %(value_var)s)" % {
  1219. "attr_name": attr_name,
  1220. "value_var": value_var,
  1221. }
  1222. def fmt_setter_with_converter(attr_name, value_var):
  1223. conv_name = _init_converter_pat.format(attr_name)
  1224. return "_setattr('%(attr_name)s', %(conv)s(%(value_var)s))" % {
  1225. "attr_name": attr_name,
  1226. "value_var": value_var,
  1227. "conv": conv_name,
  1228. }
  1229. else:
  1230. # Dict frozen classes assign directly to __dict__.
  1231. # But only if the attribute doesn't come from an ancestor slot
  1232. # class.
  1233. # Note _inst_dict will be used again below if cache_hash is True
  1234. lines.append("_inst_dict = self.__dict__")
  1235. if any_slot_ancestors:
  1236. lines.append(
  1237. # Circumvent the __setattr__ descriptor to save one lookup
  1238. # per assignment.
  1239. "_setattr = _cached_setattr.__get__(self, self.__class__)"
  1240. )
  1241. def fmt_setter(attr_name, value_var):
  1242. if _is_slot_attr(attr_name, base_attr_map):
  1243. res = "_setattr('%(attr_name)s', %(value_var)s)" % {
  1244. "attr_name": attr_name,
  1245. "value_var": value_var,
  1246. }
  1247. else:
  1248. res = "_inst_dict['%(attr_name)s'] = %(value_var)s" % {
  1249. "attr_name": attr_name,
  1250. "value_var": value_var,
  1251. }
  1252. return res
  1253. def fmt_setter_with_converter(attr_name, value_var):
  1254. conv_name = _init_converter_pat.format(attr_name)
  1255. if _is_slot_attr(attr_name, base_attr_map):
  1256. tmpl = "_setattr('%(attr_name)s', %(c)s(%(value_var)s))"
  1257. else:
  1258. tmpl = "_inst_dict['%(attr_name)s'] = %(c)s(%(value_var)s)"
  1259. return tmpl % {
  1260. "attr_name": attr_name,
  1261. "value_var": value_var,
  1262. "c": conv_name,
  1263. }
  1264. else:
  1265. # Not frozen.
  1266. def fmt_setter(attr_name, value):
  1267. return "self.%(attr_name)s = %(value)s" % {
  1268. "attr_name": attr_name,
  1269. "value": value,
  1270. }
  1271. def fmt_setter_with_converter(attr_name, value_var):
  1272. conv_name = _init_converter_pat.format(attr_name)
  1273. return "self.%(attr_name)s = %(conv)s(%(value_var)s)" % {
  1274. "attr_name": attr_name,
  1275. "value_var": value_var,
  1276. "conv": conv_name,
  1277. }
  1278. args = []
  1279. kw_only_args = []
  1280. attrs_to_validate = []
  1281. # This is a dictionary of names to validator and converter callables.
  1282. # Injecting this into __init__ globals lets us avoid lookups.
  1283. names_for_globals = {}
  1284. annotations = {"return": None}
  1285. for a in attrs:
  1286. if a.validator:
  1287. attrs_to_validate.append(a)
  1288. attr_name = a.name
  1289. arg_name = a.name.lstrip("_")
  1290. has_factory = isinstance(a.default, Factory)
  1291. if has_factory and a.default.takes_self:
  1292. maybe_self = "self"
  1293. else:
  1294. maybe_self = ""
  1295. if a.init is False:
  1296. if has_factory:
  1297. init_factory_name = _init_factory_pat.format(a.name)
  1298. if a.converter is not None:
  1299. lines.append(
  1300. fmt_setter_with_converter(
  1301. attr_name,
  1302. init_factory_name + "({0})".format(maybe_self),
  1303. )
  1304. )
  1305. conv_name = _init_converter_pat.format(a.name)
  1306. names_for_globals[conv_name] = a.converter
  1307. else:
  1308. lines.append(
  1309. fmt_setter(
  1310. attr_name,
  1311. init_factory_name + "({0})".format(maybe_self),
  1312. )
  1313. )
  1314. names_for_globals[init_factory_name] = a.default.factory
  1315. else:
  1316. if a.converter is not None:
  1317. lines.append(
  1318. fmt_setter_with_converter(
  1319. attr_name,
  1320. "attr_dict['{attr_name}'].default".format(
  1321. attr_name=attr_name
  1322. ),
  1323. )
  1324. )
  1325. conv_name = _init_converter_pat.format(a.name)
  1326. names_for_globals[conv_name] = a.converter
  1327. else:
  1328. lines.append(
  1329. fmt_setter(
  1330. attr_name,
  1331. "attr_dict['{attr_name}'].default".format(
  1332. attr_name=attr_name
  1333. ),
  1334. )
  1335. )
  1336. elif a.default is not NOTHING and not has_factory:
  1337. arg = "{arg_name}=attr_dict['{attr_name}'].default".format(
  1338. arg_name=arg_name, attr_name=attr_name
  1339. )
  1340. if a.kw_only:
  1341. kw_only_args.append(arg)
  1342. else:
  1343. args.append(arg)
  1344. if a.converter is not None:
  1345. lines.append(fmt_setter_with_converter(attr_name, arg_name))
  1346. names_for_globals[
  1347. _init_converter_pat.format(a.name)
  1348. ] = a.converter
  1349. else:
  1350. lines.append(fmt_setter(attr_name, arg_name))
  1351. elif has_factory:
  1352. arg = "{arg_name}=NOTHING".format(arg_name=arg_name)
  1353. if a.kw_only:
  1354. kw_only_args.append(arg)
  1355. else:
  1356. args.append(arg)
  1357. lines.append(
  1358. "if {arg_name} is not NOTHING:".format(arg_name=arg_name)
  1359. )
  1360. init_factory_name = _init_factory_pat.format(a.name)
  1361. if a.converter is not None:
  1362. lines.append(
  1363. " " + fmt_setter_with_converter(attr_name, arg_name)
  1364. )
  1365. lines.append("else:")
  1366. lines.append(
  1367. " "
  1368. + fmt_setter_with_converter(
  1369. attr_name,
  1370. init_factory_name + "({0})".format(maybe_self),
  1371. )
  1372. )
  1373. names_for_globals[
  1374. _init_converter_pat.format(a.name)
  1375. ] = a.converter
  1376. else:
  1377. lines.append(" " + fmt_setter(attr_name, arg_name))
  1378. lines.append("else:")
  1379. lines.append(
  1380. " "
  1381. + fmt_setter(
  1382. attr_name,
  1383. init_factory_name + "({0})".format(maybe_self),
  1384. )
  1385. )
  1386. names_for_globals[init_factory_name] = a.default.factory
  1387. else:
  1388. if a.kw_only:
  1389. kw_only_args.append(arg_name)
  1390. else:
  1391. args.append(arg_name)
  1392. if a.converter is not None:
  1393. lines.append(fmt_setter_with_converter(attr_name, arg_name))
  1394. names_for_globals[
  1395. _init_converter_pat.format(a.name)
  1396. ] = a.converter
  1397. else:
  1398. lines.append(fmt_setter(attr_name, arg_name))
  1399. if a.init is True and a.converter is None and a.type is not None:
  1400. annotations[arg_name] = a.type
  1401. if attrs_to_validate: # we can skip this if there are no validators.
  1402. names_for_globals["_config"] = _config
  1403. lines.append("if _config._run_validators is True:")
  1404. for a in attrs_to_validate:
  1405. val_name = "__attr_validator_{}".format(a.name)
  1406. attr_name = "__attr_{}".format(a.name)
  1407. lines.append(
  1408. " {}(self, {}, self.{})".format(val_name, attr_name, a.name)
  1409. )
  1410. names_for_globals[val_name] = a.validator
  1411. names_for_globals[attr_name] = a
  1412. if post_init:
  1413. lines.append("self.__attrs_post_init__()")
  1414. # because this is set only after __attrs_post_init is called, a crash
  1415. # will result if post-init tries to access the hash code. This seemed
  1416. # preferable to setting this beforehand, in which case alteration to
  1417. # field values during post-init combined with post-init accessing the
  1418. # hash code would result in silent bugs.
  1419. if cache_hash:
  1420. if frozen:
  1421. if slots:
  1422. # if frozen and slots, then _setattr defined above
  1423. init_hash_cache = "_setattr('%s', %s)"
  1424. else:
  1425. # if frozen and not slots, then _inst_dict defined above
  1426. init_hash_cache = "_inst_dict['%s'] = %s"
  1427. else:
  1428. init_hash_cache = "self.%s = %s"
  1429. lines.append(init_hash_cache % (_hash_cache_field, "None"))
  1430. # For exceptions we rely on BaseException.__init__ for proper
  1431. # initialization.
  1432. if is_exc:
  1433. vals = ",".join("self." + a.name for a in attrs if a.init)
  1434. lines.append("BaseException.__init__(self, %s)" % (vals,))
  1435. args = ", ".join(args)
  1436. if kw_only_args:
  1437. if PY2:
  1438. raise PythonTooOldError(
  1439. "Keyword-only arguments only work on Python 3 and later."
  1440. )
  1441. args += "{leading_comma}*, {kw_only_args}".format(
  1442. leading_comma=", " if args else "",
  1443. kw_only_args=", ".join(kw_only_args),
  1444. )
  1445. return (
  1446. """\
  1447. def __init__(self, {args}):
  1448. {lines}
  1449. """.format(
  1450. args=args, lines="\n ".join(lines) if lines else "pass"
  1451. ),
  1452. names_for_globals,
  1453. annotations,
  1454. )
  1455. class Attribute(object):
  1456. """
  1457. *Read-only* representation of an attribute.
  1458. :attribute name: The name of the attribute.
  1459. Plus *all* arguments of `attr.ib` (except for ``factory``
  1460. which is only syntactic sugar for ``default=Factory(...)``.
  1461. For the version history of the fields, see `attr.ib`.
  1462. """
  1463. __slots__ = (
  1464. "name",
  1465. "default",
  1466. "validator",
  1467. "repr",
  1468. "eq",
  1469. "order",
  1470. "hash",
  1471. "init",
  1472. "metadata",
  1473. "type",
  1474. "converter",
  1475. "kw_only",
  1476. )
  1477. def __init__(
  1478. self,
  1479. name,
  1480. default,
  1481. validator,
  1482. repr,
  1483. cmp, # XXX: unused, remove along with other cmp code.
  1484. hash,
  1485. init,
  1486. metadata=None,
  1487. type=None,
  1488. converter=None,
  1489. kw_only=False,
  1490. eq=None,
  1491. order=None,
  1492. ):
  1493. eq, order = _determine_eq_order(cmp, eq, order)
  1494. # Cache this descriptor here to speed things up later.
  1495. bound_setattr = _obj_setattr.__get__(self, Attribute)
  1496. # Despite the big red warning, people *do* instantiate `Attribute`
  1497. # themselves.
  1498. bound_setattr("name", name)
  1499. bound_setattr("default", default)
  1500. bound_setattr("validator", validator)
  1501. bound_setattr("repr", repr)
  1502. bound_setattr("eq", eq)
  1503. bound_setattr("order", order)
  1504. bound_setattr("hash", hash)
  1505. bound_setattr("init", init)
  1506. bound_setattr("converter", converter)
  1507. bound_setattr(
  1508. "metadata",
  1509. (
  1510. metadata_proxy(metadata)
  1511. if metadata
  1512. else _empty_metadata_singleton
  1513. ),
  1514. )
  1515. bound_setattr("type", type)
  1516. bound_setattr("kw_only", kw_only)
  1517. def __setattr__(self, name, value):
  1518. raise FrozenInstanceError()
  1519. @classmethod
  1520. def from_counting_attr(cls, name, ca, type=None):
  1521. # type holds the annotated value. deal with conflicts:
  1522. if type is None:
  1523. type = ca.type
  1524. elif ca.type is not None:
  1525. raise ValueError(
  1526. "Type annotation and type argument cannot both be present"
  1527. )
  1528. inst_dict = {
  1529. k: getattr(ca, k)
  1530. for k in Attribute.__slots__
  1531. if k
  1532. not in (
  1533. "name",
  1534. "validator",
  1535. "default",
  1536. "type",
  1537. ) # exclude methods and deprecated alias
  1538. }
  1539. return cls(
  1540. name=name,
  1541. validator=ca._validator,
  1542. default=ca._default,
  1543. type=type,
  1544. cmp=None,
  1545. **inst_dict
  1546. )
  1547. @property
  1548. def cmp(self):
  1549. """
  1550. Simulate the presence of a cmp attribute and warn.
  1551. """
  1552. warnings.warn(_CMP_DEPRECATION, DeprecationWarning, stacklevel=2)
  1553. return self.eq and self.order
  1554. # Don't use attr.assoc since fields(Attribute) doesn't work
  1555. def _assoc(self, **changes):
  1556. """
  1557. Copy *self* and apply *changes*.
  1558. """
  1559. new = copy.copy(self)
  1560. new._setattrs(changes.items())
  1561. return new
  1562. # Don't use _add_pickle since fields(Attribute) doesn't work
  1563. def __getstate__(self):
  1564. """
  1565. Play nice with pickle.
  1566. """
  1567. return tuple(
  1568. getattr(self, name) if name != "metadata" else dict(self.metadata)
  1569. for name in self.__slots__
  1570. )
  1571. def __setstate__(self, state):
  1572. """
  1573. Play nice with pickle.
  1574. """
  1575. self._setattrs(zip(self.__slots__, state))
  1576. def _setattrs(self, name_values_pairs):
  1577. bound_setattr = _obj_setattr.__get__(self, Attribute)
  1578. for name, value in name_values_pairs:
  1579. if name != "metadata":
  1580. bound_setattr(name, value)
  1581. else:
  1582. bound_setattr(
  1583. name,
  1584. metadata_proxy(value)
  1585. if value
  1586. else _empty_metadata_singleton,
  1587. )
  1588. _a = [
  1589. Attribute(
  1590. name=name,
  1591. default=NOTHING,
  1592. validator=None,
  1593. repr=True,
  1594. cmp=None,
  1595. eq=True,
  1596. order=False,
  1597. hash=(name != "metadata"),
  1598. init=True,
  1599. )
  1600. for name in Attribute.__slots__
  1601. ]
  1602. Attribute = _add_hash(
  1603. _add_eq(_add_repr(Attribute, attrs=_a), attrs=_a),
  1604. attrs=[a for a in _a if a.hash],
  1605. )
  1606. class _CountingAttr(object):
  1607. """
  1608. Intermediate representation of attributes that uses a counter to preserve
  1609. the order in which the attributes have been defined.
  1610. *Internal* data structure of the attrs library. Running into is most
  1611. likely the result of a bug like a forgotten `@attr.s` decorator.
  1612. """
  1613. __slots__ = (
  1614. "counter",
  1615. "_default",
  1616. "repr",
  1617. "eq",
  1618. "order",
  1619. "hash",
  1620. "init",
  1621. "metadata",
  1622. "_validator",
  1623. "converter",
  1624. "type",
  1625. "kw_only",
  1626. )
  1627. __attrs_attrs__ = tuple(
  1628. Attribute(
  1629. name=name,
  1630. default=NOTHING,
  1631. validator=None,
  1632. repr=True,
  1633. cmp=None,
  1634. hash=True,
  1635. init=True,
  1636. kw_only=False,
  1637. eq=True,
  1638. order=False,
  1639. )
  1640. for name in (
  1641. "counter",
  1642. "_default",
  1643. "repr",
  1644. "eq",
  1645. "order",
  1646. "hash",
  1647. "init",
  1648. )
  1649. ) + (
  1650. Attribute(
  1651. name="metadata",
  1652. default=None,
  1653. validator=None,
  1654. repr=True,
  1655. cmp=None,
  1656. hash=False,
  1657. init=True,
  1658. kw_only=False,
  1659. eq=True,
  1660. order=False,
  1661. ),
  1662. )
  1663. cls_counter = 0
  1664. def __init__(
  1665. self,
  1666. default,
  1667. validator,
  1668. repr,
  1669. cmp, # XXX: unused, remove along with cmp
  1670. hash,
  1671. init,
  1672. converter,
  1673. metadata,
  1674. type,
  1675. kw_only,
  1676. eq,
  1677. order,
  1678. ):
  1679. _CountingAttr.cls_counter += 1
  1680. self.counter = _CountingAttr.cls_counter
  1681. self._default = default
  1682. # If validator is a list/tuple, wrap it using helper validator.
  1683. if validator and isinstance(validator, (list, tuple)):
  1684. self._validator = and_(*validator)
  1685. else:
  1686. self._validator = validator
  1687. self.repr = repr
  1688. self.eq = eq
  1689. self.order = order
  1690. self.hash = hash
  1691. self.init = init
  1692. self.converter = converter
  1693. self.metadata = metadata
  1694. self.type = type
  1695. self.kw_only = kw_only
  1696. def validator(self, meth):
  1697. """
  1698. Decorator that adds *meth* to the list of validators.
  1699. Returns *meth* unchanged.
  1700. .. versionadded:: 17.1.0
  1701. """
  1702. if self._validator is None:
  1703. self._validator = meth
  1704. else:
  1705. self._validator = and_(self._validator, meth)
  1706. return meth
  1707. def default(self, meth):
  1708. """
  1709. Decorator that allows to set the default for an attribute.
  1710. Returns *meth* unchanged.
  1711. :raises DefaultAlreadySetError: If default has been set before.
  1712. .. versionadded:: 17.1.0
  1713. """
  1714. if self._default is not NOTHING:
  1715. raise DefaultAlreadySetError()
  1716. self._default = Factory(meth, takes_self=True)
  1717. return meth
  1718. _CountingAttr = _add_eq(_add_repr(_CountingAttr))
  1719. @attrs(slots=True, init=False, hash=True)
  1720. class Factory(object):
  1721. """
  1722. Stores a factory callable.
  1723. If passed as the default value to `attr.ib`, the factory is used to
  1724. generate a new value.
  1725. :param callable factory: A callable that takes either none or exactly one
  1726. mandatory positional argument depending on *takes_self*.
  1727. :param bool takes_self: Pass the partially initialized instance that is
  1728. being initialized as a positional argument.
  1729. .. versionadded:: 17.1.0 *takes_self*
  1730. """
  1731. factory = attrib()
  1732. takes_self = attrib()
  1733. def __init__(self, factory, takes_self=False):
  1734. """
  1735. `Factory` is part of the default machinery so if we want a default
  1736. value here, we have to implement it ourselves.
  1737. """
  1738. self.factory = factory
  1739. self.takes_self = takes_self
  1740. def make_class(name, attrs, bases=(object,), **attributes_arguments):
  1741. """
  1742. A quick way to create a new class called *name* with *attrs*.
  1743. :param name: The name for the new class.
  1744. :type name: str
  1745. :param attrs: A list of names or a dictionary of mappings of names to
  1746. attributes.
  1747. If *attrs* is a list or an ordered dict (`dict` on Python 3.6+,
  1748. `collections.OrderedDict` otherwise), the order is deduced from
  1749. the order of the names or attributes inside *attrs*. Otherwise the
  1750. order of the definition of the attributes is used.
  1751. :type attrs: `list` or `dict`
  1752. :param tuple bases: Classes that the new class will subclass.
  1753. :param attributes_arguments: Passed unmodified to `attr.s`.
  1754. :return: A new class with *attrs*.
  1755. :rtype: type
  1756. .. versionadded:: 17.1.0 *bases*
  1757. .. versionchanged:: 18.1.0 If *attrs* is ordered, the order is retained.
  1758. """
  1759. if isinstance(attrs, dict):
  1760. cls_dict = attrs
  1761. elif isinstance(attrs, (list, tuple)):
  1762. cls_dict = dict((a, attrib()) for a in attrs)
  1763. else:
  1764. raise TypeError("attrs argument must be a dict or a list.")
  1765. post_init = cls_dict.pop("__attrs_post_init__", None)
  1766. type_ = type(
  1767. name,
  1768. bases,
  1769. {} if post_init is None else {"__attrs_post_init__": post_init},
  1770. )
  1771. # For pickling to work, the __module__ variable needs to be set to the
  1772. # frame where the class is created. Bypass this step in environments where
  1773. # sys._getframe is not defined (Jython for example) or sys._getframe is not
  1774. # defined for arguments greater than 0 (IronPython).
  1775. try:
  1776. type_.__module__ = sys._getframe(1).f_globals.get(
  1777. "__name__", "__main__"
  1778. )
  1779. except (AttributeError, ValueError):
  1780. pass
  1781. # We do it here for proper warnings with meaningful stacklevel.
  1782. cmp = attributes_arguments.pop("cmp", None)
  1783. attributes_arguments["eq"], attributes_arguments[
  1784. "order"
  1785. ] = _determine_eq_order(
  1786. cmp, attributes_arguments.get("eq"), attributes_arguments.get("order")
  1787. )
  1788. return _attrs(these=cls_dict, **attributes_arguments)(type_)
  1789. # These are required by within this module so we define them here and merely
  1790. # import into .validators.
  1791. @attrs(slots=True, hash=True)
  1792. class _AndValidator(object):
  1793. """
  1794. Compose many validators to a single one.
  1795. """
  1796. _validators = attrib()
  1797. def __call__(self, inst, attr, value):
  1798. for v in self._validators:
  1799. v(inst, attr, value)
  1800. def and_(*validators):
  1801. """
  1802. A validator that composes multiple validators into one.
  1803. When called on a value, it runs all wrapped validators.
  1804. :param validators: Arbitrary number of validators.
  1805. :type validators: callables
  1806. .. versionadded:: 17.1.0
  1807. """
  1808. vals = []
  1809. for validator in validators:
  1810. vals.extend(
  1811. validator._validators
  1812. if isinstance(validator, _AndValidator)
  1813. else [validator]
  1814. )
  1815. return _AndValidator(tuple(vals))