U aX@sdddlmZmZmZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z mZddlmZmZmZmZmZmZmZddlmZmZmZmZmZejZdZ d Z!d Z"d Z#d Z$eiZ%eZ&Gd ddeZ'e'Z(Gddde)Z*e(dddddddddddddfddZ+ddZ,e,ddddgZ-ddZ.ddZ/dd Z0d!d"Z1d#d$Z2d%d&Z3d'd(Z4ertd)d*Z5nd+d*Z5d,d-Z6Gd.d/d/eZ7d0Z8d1d2Z9d|d3d4Z:d}d5dZ;e;Zd;d<Z?d=d>Z@d?d@ZAdAdBZBdCdDZCdEdFZDd~dGdHZEeFZGdIdJZHddKdLZIdMdNZJdOdPZKdQdRZLdSdTZMdUdVZNdWdXZOdYdZZPd[d\ZQd]d^ZRd_d`ZSerddadbZTdcddZUdedfZVGdgdhdheZWdidjeWjXDZYeAeEeIeWeYdkdldjeYDdkdmdjeYDdkZWGdndodoeZZeEeIeZZZe;ddddpGdqdrdreZ[effdsdtZ\e;ddduGdvdwdweZ]dxdyZ^dzd{Z_dS))absolute_importdivisionprint_functionN) itemgetter)_configsetters)PY2PYPYisclass iteritemsmetadata_proxy ordered_dictset_closure_cell)DefaultAlreadySetErrorFrozenInstanceErrorNotAnAttrsClassErrorPythonTooOldErrorUnannotatedAttributeErrorz__attr_converter_%sz__attr_factory_{}z= {attr_name} = _attrs_property(_attrs_itemgetter({index})))ztyping.ClassVarz t.ClassVarClassVarZ_attrs_cached_hashcs,eZdZdZdZfddZddZZS)_Nothingz Sentinel class to indicate the lack of a value when ``None`` is ambiguous. ``_Nothing`` is a singleton. There is only ever one of it. Ncs"tjdkrtt||t_tjSN)r _singletonsuper__new__cls __class__/Users/jalaguru/Documents/Proserv/artifacts/aws_dms_cdk_automation/aws-dms-cdk-automation/venv/lib/python3.8/site-packages/attr/_make.pyr;s z_Nothing.__new__cCsdS)NNOTHINGrselfrrr __repr__@sz_Nothing.__repr__)__name__ __module__ __qualname____doc__rrr$ __classcell__rrrr r2s rc@s6eZdZdZer edfddZneddfddZdS)_CacheHashWrappera An integer subclass that pickles / copies as None This is used for non-slots classes with ``cache_hash=True``, to avoid serializing a potentially (even likely) invalid hash value. Since ``None`` is the default value for uncalculated hashes, whenever this is copied, the copy's value for the hash should automatically reset. See GH #613 for more details. )rNcCs||fSrrr#Z_none_constructor_argsrrr __reduce__Zsz_CacheHashWrapper.__reduce__NrcCs||fSrrr,rrr r._s)r%r&r'r(r getattrr.typerrrr r*Js r*TFcCst|| | d\} } |dk r2|dk r2|dk r2td| dk rb|tk rJtdt| sZtdt| }|dkrni}t| ttfrt j | } |rt|ttfrt |}|rt|ttfrt |}t |||d|||||| | | | d S)aG Create a new attribute on a class. .. warning:: Does *not* do anything unless the class is also decorated with `attr.s`! :param default: A value that is used if an ``attrs``-generated ``__init__`` is used and no value is passed while instantiating or the attribute is excluded using ``init=False``. If the value is an instance of `Factory`, its callable will be used to construct a new value (useful for mutable data types like lists or dicts). If a default is not set (or set manually to `attr.NOTHING`), a value *must* be supplied when instantiating; otherwise a `TypeError` will be raised. The default can also be set using decorator notation as shown below. :type default: Any value :param callable factory: Syntactic sugar for ``default=attr.Factory(factory)``. :param validator: `callable` that is called by ``attrs``-generated ``__init__`` methods after the instance has been initialized. They receive the initialized instance, the `Attribute`, and the passed value. The return value is *not* inspected so the validator has to throw an exception itself. If a `list` is passed, its items are treated as validators and must all pass. Validators can be globally disabled and re-enabled using `get_run_validators`. The validator can also be set using decorator notation as shown below. :type validator: `callable` or a `list` of `callable`\ s. :param repr: Include this attribute in the generated ``__repr__`` method. If ``True``, include the attribute; if ``False``, omit it. By default, the built-in ``repr()`` function is used. To override how the attribute value is formatted, pass a ``callable`` that takes a single value and returns a string. Note that the resulting string is used as-is, i.e. it will be used directly *instead* of calling ``repr()`` (the default). :type repr: a `bool` or a `callable` to use a custom function. :param bool eq: If ``True`` (default), include this attribute in the generated ``__eq__`` and ``__ne__`` methods that check two instances for equality. :param bool order: If ``True`` (default), include this attributes in the generated ``__lt__``, ``__le__``, ``__gt__`` and ``__ge__`` methods. :param bool cmp: Setting to ``True`` is equivalent to setting ``eq=True, order=True``. Deprecated in favor of *eq* and *order*. :param Optional[bool] hash: Include this attribute in the generated ``__hash__`` method. If ``None`` (default), mirror *eq*'s value. This is the correct behavior according the Python spec. Setting this value to anything else than ``None`` is *discouraged*. :param bool init: Include this attribute in the generated ``__init__`` method. It is possible to set this to ``False`` and set a default value. In that case this attributed is unconditionally initialized with the specified default value or factory. :param callable converter: `callable` that is called by ``attrs``-generated ``__init__`` methods to convert attribute's value to the desired format. It is given the passed-in value, and the returned value will be used as the new value of the attribute. The value is converted before being passed to the validator, if any. :param metadata: An arbitrary mapping, to be used by third-party components. See `extending_metadata`. :param type: The type of the attribute. In Python 3.6 or greater, the preferred method to specify the type is using a variable annotation (see `PEP 526 `_). This argument is provided for backward compatibility. Regardless of the approach used, the type will be stored on ``Attribute.type``. Please note that ``attrs`` doesn't do anything with this metadata by itself. You can use it as part of your own code or for `static type checking `. :param kw_only: Make this attribute keyword-only (Python 3+) in the generated ``__init__`` (if ``init`` is ``False``, this parameter is ignored). :param on_setattr: Allows to overwrite the *on_setattr* setting from `attr.s`. If left `None`, the *on_setattr* value from `attr.s` is used. Set to `attr.setters.NO_OP` to run **no** `setattr` hooks for this attribute -- regardless of the setting in `attr.s`. :type on_setattr: `callable`, or a list of callables, or `None`, or `attr.setters.NO_OP` .. versionadded:: 15.2.0 *convert* .. versionadded:: 16.3.0 *metadata* .. versionchanged:: 17.1.0 *validator* can be a ``list`` now. .. versionchanged:: 17.1.0 *hash* is ``None`` and therefore mirrors *eq* by default. .. versionadded:: 17.3.0 *type* .. deprecated:: 17.4.0 *convert* .. versionadded:: 17.4.0 *converter* as a replacement for the deprecated *convert* to achieve consistency with other noun-based arguments. .. versionadded:: 18.1.0 ``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``. .. versionadded:: 18.2.0 *kw_only* .. versionchanged:: 19.2.0 *convert* keyword argument removed .. versionchanged:: 19.2.0 *repr* also accepts a custom callable. .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01. .. versionadded:: 19.2.0 *eq* and *order* .. versionadded:: 20.1.0 *on_setattr* .. versionchanged:: 20.3.0 *kw_only* backported to Python 2 TNF6Invalid value for hash. Must be True, False, or None.z=The `default` and `factory` arguments are mutually exclusive.z*The `factory` argument must be a callable.) default validatorreprcmphashinit convertermetadatar0kw_onlyeqorder on_setattr) _determine_eq_order TypeErrorr! ValueErrorcallableFactory isinstancelisttuplerpipeand_ _CountingAttr)r2r3r4r5r6r7r9r0r8factoryr:r;r<r=rrr attribcsJ rJcCsxd|}d|dg}|rDt|D]\}}|tj||dq$n |dttd}ttd|dd |||S) z Create a tuple subclass to hold `Attribute`s for an `attrs` class. The subclass is a bare tuple with properties for names. class MyClassAttributes(tuple): __slots__ = () x = property(itemgetter(0)) z {}Attributeszclass {}(tuple):z __slots__ = ())index attr_namez pass)Z_attrs_itemgetterZ_attrs_property r+exec) format enumerateappend_tuple_property_patrpropertyevalcompilejoin)Zcls_name attr_namesZattr_class_nameZattr_class_templateirLglobsrrr _make_attr_tuple_classs    rZ _Attributesattrs base_attrsZbase_attrs_mapcCst|tS)z Check whether *annot* is a typing.ClassVar. The string comparison hack is used to avoid evaluating all string annotations which would put attrs-based classes at a performance disadvantage compared to plain old classes. )str startswith_classvar_prefixes)Zannotrrr _is_class_var?sracCsJt||t}|tkrdS|jddD]}t||d}||kr&dSq&dS)zj Check whether *cls* defines *attrib_name* (and doesn't just inherit it). Requires Python 3. FrNT)r/ _sentinel__mro__)rZ attrib_nameattrbase_clsarrr _has_own_attributeJs  rgcCst|dr|jSiS)z$ Get annotations for *cls*. __annotations__)rgrhrrrr _get_annotations\s ricCs |djS)zQ Key function for sorting to avoid re-creating a lambda for every class. rcountererrr _counter_getterfsrncCsg}i}t|jddD]H}t|dgD]6}|js*|j|kr@q*|jdd}|||||j<q*qg}t}t|D](}|j|krqv|d|| |jqv||fS)zQ Collect attr.ibs from base classes of *cls*, except *taken_attr_names*. r__attrs_attrs__T inheritedr) reversedrcr/rrnameevolverQsetinsertadd)rtaken_attr_namesr] base_attr_maprerffilteredseenrrr _collect_base_attrsms"     r}cCsng}i}|jddD]N}t|dgD]<}|j|kr6q&|jdd}||j|||||j<q&q||fS)a- Collect attr.ibs from base classes of *cls*, except *taken_attr_names*. N.B. *taken_attr_names* will be mutated. Adhere to the old incorrect behavior. Notably it collects from the front and considers inherited attributes which leads to the buggy behavior reported in #428. rrorpTrq)rcr/rtrurxrQ)rryr]rzrerfrrr _collect_base_attrs_brokens     r~c s6|jt||dk r@ddt|D}t|ts>|jtdn|dkrddD}g}t}D]Z\} } t | rqn| |  | t } t| t s| t krt} n t| d} || | fqn||} t| d kr&td d t| fd d ddntddDdd d}fdd|D} |rXt|dd| D\}}nt|dd| D\}}dd|| D}t|j|}|rdd| D} dd|D}||| }d}dd|DD]D} |dkr| jt krtd| f|dkr| jt k rd}q|dk r(|||}t|||fS)a0 Transform all `_CountingAttr`s on a class into `Attribute`s. If *these* is passed, use that and don't look for them on the class. *collect_by_mro* is True, collect them in the correct MRO order, otherwise use the old -- incorrect -- order. See #428. Return an `_Attributes`. NcSsg|]\}}||fqSrr).0rtcarrr sz$_transform_attrs..)keyTcSsh|]\}}t|tr|qSrrCrHrrtrdrrr s z#_transform_attrs..r2rz1The following `attr.ib`s lack a type annotation: , cs |jSr)getrk)n)cdrr z"_transform_attrs...css$|]\}}t|tr||fVqdSrrrrrr s z#_transform_attrs..cSs |djSNrrjrlrrr rrcs&g|]\}}tj|||dqS))rtrr0) Attributefrom_counting_attrr)rrLr)annsrr rs cSsh|] }|jqSrrtrrfrrr rscSsh|] }|jqSrrrrrr rscSsg|] }|jqSrrrrrr rscSsg|]}|jddqST)r:rurrrr rscSsg|]}|jddqSrrrrrr rsFcss&|]}|jdk r|jdkr|VqdS)FN)r7r:rrrr rs znNo mandatory attributes allowed after an attribute with a default value or factory. Attribute in question: %r)__dict__rir rCrsortrnitemsrvrarxrr!rHrJrQlenrrVsortedr}r~rZr%r2r@r[)rthese auto_attribsr:collect_by_mrofield_transformerZca_listZca_namesZ annot_namesrLr0rfZ unannotatedZ own_attrsr]rzrWZ AttrsClassr\Z had_defaultr)rrr _transform_attrss              rcCs.t|tr$|dkr$t|||dStdS)< Attached to frozen classes as __setattr__. ) __cause__ __context__N)rC BaseException __setattr__rr#rtvaluerrr _frozen_setattrssrcCs tdS)rNrrrrr r%scCs tdS)z4 Attached to frozen classes as __delattr__. Nr)r#rtrrr _frozen_delattrs,src@seZdZdZdZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZddZddZddZddZdd Zd!S)" _ClassBuilderz( Iteratively build *one* class. ) _attr_names_attrs_base_attr_map _base_names _cache_hash_cls _cls_dict_delete_attribs_frozen_has_post_init_is_exc _on_setattr_slots _weakref_slot_has_own_setattr_has_custom_setattrcCst||||| |\}}}||_|r,t|jni|_||_tdd|D|_||_t dd|D|_ ||_ ||_ ||_ | |_tt|dd|_t| |_| |_| |_| |_d|_|j|jd<|rt|jd<t|jd<d |_|r|\|jd <|jd <dS) Ncss|] }|jVqdSrrrrrr rhsz)_ClassBuilder.__init__..css|] }|jVqdSrrrrrr rjs__attrs_post_init__Frpr __delattr__T __getstate__ __setstate__)rrdictrrrrvrrrErrrrrboolr/rrrrrrrr_make_getstate_setstate)r#rrslotsfrozen weakref_slotgetstate_setstaterr: cache_hashis_excrr=Zhas_custom_setattrrr\r]Zbase_maprrr __init__KsF     z_ClassBuilder.__init__cCsdj|jjdS)Nz<_ClassBuilder(cls={cls})>r)rOrr%r"rrr r$sz_ClassBuilder.__repr__cCs|jdkr|S|SdS)z Finalize class based on the accumulated configuration. Builder cannot be used after calling this method. TN)r_create_slots_class_patch_original_classr"rrr build_classs z_ClassBuilder.build_classc Cs|j}|j}|jrZ|jD]@}||krt||ttk rzt||Wqtk rVYqXq|j D]\}}t |||qd|j st|ddrd|_ |j stj|_|S)zA Apply accumulated methods and return the class. __attrs_own_setattr__F)rrrrr/rbdelattrAttributeErrorrrsetattrrrrobjectr)r#r base_namesrtrrrr rs. z#_ClassBuilder._patch_original_classc sjfddtjD}js\d|d<js\jjD] }|jddr:t j |d<q\q:d}jj ddD]}|jdd d k rpd }qqpj }j rdtjd d krd|kr|s|d 7}fdd|D}jr|tt||d <tjdd }|d k r||d<tjjjjj|}|jD]}t|ttfrXt|jdd } n t|dd } | snq4| D]>} z| jjk} Wntk rYnX| rrt| |qrq4|S)zL Build and return a new class with a `__slots__` attribute. cs(i|] \}}|tjdkr||qS))r __weakref__)rEr)rkvr"rr sz5_ClassBuilder._create_slots_class..FrrrrorNT __slots__r)rcsg|]}|kr|qSrrrrt)rrr rsz5_ClassBuilder._create_slots_class..r' __closure__)rr rrrr __bases__rrrrrcrrr/rrQ_hash_cache_fieldrEr0r%valuesrC classmethod staticmethod__func__ cell_contentsr@r) r#rreZweakref_inheritednamesZ slot_namesqualnameritemZ closure_cellscellmatchr)rr#r rs`       z!_ClassBuilder._create_slots_classcCs|t|j|d|jd<|S)N)nsr$)_add_method_dunders _make_reprrr)r#rrrr add_reprs z_ClassBuilder.add_reprcCs8|jd}|dkrtddd}|||jd<|S)Nr$z3__str__ can only be generated if a __repr__ exists.cSs|Srr$r"rrr __str__sz&_ClassBuilder.add_str..__str__r)rrr@r)r#r4rrrr add_strs z_ClassBuilder.add_strcs<tdd|jDfdd}|jfdd}||fS)zF Create custom __setstate__ and __getstate__ methods. css|]}|dkr|VqdS)rNr)rZanrrr r&sz8_ClassBuilder._make_getstate_setstate..cstfddDS)9 Automatically created by attrs. c3s|]}t|VqdSrr/rr"rr r.szP_ClassBuilder._make_getstate_setstate..slots_getstate..rEr")state_attr_namesr"r slots_getstate*sz=_ClassBuilder._make_getstate_setstate..slots_getstatecs<t|t}t|D]\}}|||qr8|tddS)rN) _obj_setattr__get__rzipr)r#stateZ_ClassBuilder__bound_setattrrtrZhash_caching_enabledrrr slots_setstate2s   z=_ClassBuilder._make_getstate_setstate..slots_setstate)rErr)r#rrrrr r!s z%_ClassBuilder._make_getstate_setstatecCsd|jd<|S)N__hash__)rr"rrr make_unhashableCs z_ClassBuilder.make_unhashablecCs(|t|j|j|j|jd|jd<|S)Nrrr)r _make_hashrrrrrr"rrr add_hashGs z_ClassBuilder.add_hashc CsJ|t|j|j|j|j|j|j|j|j |j dk o:|j t j k |j d<|S)Nr)r _make_initrrrrrrrrrrNO_OPrr"rrr add_initSs   z_ClassBuilder.add_initcCs2|j}|t|j|j|d<|t|d<|S)N__eq____ne__)rr_make_eqrr_make_ner#rrrr add_eqes  z_ClassBuilder.add_eqcs>j}fddtjjD\|d<|d<|d<|d<S)Nc3s|]}|VqdSr)r)rmethr"rr rrsz*_ClassBuilder.add_order..__lt____le____gt____ge__)r _make_orderrrrrr"r add_orderos   z_ClassBuilder.add_ordercs|jr |Si|jD],}|jp"|j}|r|tjk r||f|j<qsJ|S|jrXtdfdd}d|j d<| ||j d<d|_ |S)Nz7Can't combine custom __setattr__ with on_setattr hooks.csFz|\}}Wntk r(|}YnX||||}t|||dSr)KeyErrorr)r#rtvalrfhookZnvalZsa_attrsrr rs   z._ClassBuilder.add_setattr..__setattr__Trr) rrr=rrrrtrr@rrr)r#rfr=rrrr add_setattrys$   z_ClassBuilder.add_setattrcCsz|jj|_Wntk r"YnXzd|jj|jf|_Wntk rRYnXzd|jjf|_Wntk r|YnX|S)zL Add __module__ and __qualname__ to a *method* if possible. rz'Method generated by attrs for class %s.)rr&rrVr'r%r()r#methodrrr rs"  z!_ClassBuilder._add_method_dundersN)r%r&r'r(rrr$rrrrrrrrrrr rrrrrr r3s": &U "   $rzrThe usage of `cmp` is deprecated and will be removed on or after 2021-06-01. Please use `eq` and `order` instead.cCs||dk r$t|dk |dk fr$td|dk rDtjttdd||fS|dkrP|}|dkr\|}|dkrt|dkrttd||fS)z Validate the combination of *cmp*, *eq*, and *order*. Derive the effective values of eq and order. If *eq* is None, set it to *default_eq*. Nz&Don't mix `cmp` with `eq' and `order`. stacklevelFTz-`order` can only be True if `eq` is True too.)anyr@warningswarn_CMP_DEPRECATIONDeprecationWarning)r5r;r<Z default_eqrrr r>sr>cCsF|dks|dkr|S|dkr(|dkr(|S|D]}t||r,dSq,|S)a Check whether we should implement a set of methods for *cls*. *flag* is the argument passed into @attr.s like 'init', *auto_detect* the same as passed into @attr.s and *dunders* is a tuple of attribute names whose presence signal that the user has implemented it themselves. Return *default* if no reason for either for or against is found. auto_detect must be False on Python 2. TFN)rg)rflag auto_detectZdundersr2Zdunderrrr _determine_whether_to_implements rcsrtrtdt|||d\ | t ttfr>tj  fdd}|dkr||S||SdS)a/ A class decorator that adds `dunder `_\ -methods according to the specified attributes using `attr.ib` or the *these* argument. :param these: A dictionary of name to `attr.ib` mappings. This is useful to avoid the definition of your attributes within the class body because you can't (e.g. if you want to add ``__repr__`` methods to Django models) or don't want to. If *these* is not ``None``, ``attrs`` will *not* search the class body for attributes and will *not* remove any attributes from it. If *these* is an ordered dict (`dict` on Python 3.6+, `collections.OrderedDict` otherwise), the order is deduced from the order of the attributes inside *these*. Otherwise the order of the definition of the attributes is used. :type these: `dict` of `str` to `attr.ib` :param str repr_ns: When using nested classes, there's no way in Python 2 to automatically detect that. Therefore it's possible to set the namespace explicitly for a more meaningful ``repr`` output. :param bool auto_detect: Instead of setting the *init*, *repr*, *eq*, *order*, and *hash* arguments explicitly, assume they are set to ``True`` **unless any** of the involved methods for one of the arguments is implemented in the *current* class (i.e. it is *not* inherited from some base class). So for example by implementing ``__eq__`` on a class yourself, ``attrs`` will deduce ``eq=False`` and won't create *neither* ``__eq__`` *nor* ``__ne__`` (but Python classes come with a sensible ``__ne__`` by default, so it *should* be enough to only implement ``__eq__`` in most cases). .. warning:: If you prevent ``attrs`` from creating the ordering methods for you (``order=False``, e.g. by implementing ``__le__``), it becomes *your* responsibility to make sure its ordering is sound. The best way is to use the `functools.total_ordering` decorator. Passing ``True`` or ``False`` to *init*, *repr*, *eq*, *order*, *cmp*, or *hash* overrides whatever *auto_detect* would determine. *auto_detect* requires Python 3. Setting it ``True`` on Python 2 raises a `PythonTooOldError`. :param bool repr: Create a ``__repr__`` method with a human readable representation of ``attrs`` attributes.. :param bool str: Create a ``__str__`` method that is identical to ``__repr__``. This is usually not necessary except for `Exception`\ s. :param Optional[bool] eq: If ``True`` or ``None`` (default), add ``__eq__`` and ``__ne__`` methods that check two instances for equality. They compare the instances as if they were tuples of their ``attrs`` attributes if and only if the types of both classes are *identical*! :param Optional[bool] order: If ``True``, add ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` methods that behave like *eq* above and allow instances to be ordered. If ``None`` (default) mirror value of *eq*. :param Optional[bool] cmp: Setting to ``True`` is equivalent to setting ``eq=True, order=True``. Deprecated in favor of *eq* and *order*, has precedence over them for backward-compatibility though. Must not be mixed with *eq* or *order*. :param Optional[bool] hash: If ``None`` (default), the ``__hash__`` method is generated according how *eq* and *frozen* are set. 1. If *both* are True, ``attrs`` will generate a ``__hash__`` for you. 2. If *eq* is True and *frozen* is False, ``__hash__`` will be set to None, marking it unhashable (which it is). 3. If *eq* is False, ``__hash__`` will be left untouched meaning the ``__hash__`` method of the base class will be used (if base class is ``object``, this means it will fall back to id-based hashing.). Although not recommended, you can decide for yourself and force ``attrs`` to create one (e.g. if the class is immutable even though you didn't freeze it programmatically) by passing ``True`` or not. Both of these cases are rather special and should be used carefully. See our documentation on `hashing`, Python's documentation on `object.__hash__`, and the `GitHub issue that led to the default \ behavior `_ for more details. :param bool init: Create a ``__init__`` method that initializes the ``attrs`` attributes. Leading underscores are stripped for the argument name. If a ``__attrs_post_init__`` method exists on the class, it will be called after the class is fully initialized. :param bool slots: Create a `slotted class ` that's more memory-efficient. Slotted classes are generally superior to the default dict classes, but have some gotchas you should know about, so we encourage you to read the `glossary entry `. :param bool frozen: Make instances immutable after initialization. If someone attempts to modify a frozen instance, `attr.exceptions.FrozenInstanceError` is raised. .. note:: 1. This is achieved by installing a custom ``__setattr__`` method on your class, so you can't implement your own. 2. True immutability is impossible in Python. 3. This *does* have a minor a runtime performance `impact ` when initializing new instances. In other words: ``__init__`` is slightly slower with ``frozen=True``. 4. If a class is frozen, you cannot modify ``self`` in ``__attrs_post_init__`` or a self-written ``__init__``. You can circumvent that limitation by using ``object.__setattr__(self, "attribute_name", value)``. 5. Subclasses of a frozen class are frozen too. :param bool weakref_slot: Make instances weak-referenceable. This has no effect unless ``slots`` is also enabled. :param bool auto_attribs: If ``True``, collect `PEP 526`_-annotated attributes (Python 3.6 and later only) from the class body. In this case, you **must** annotate every field. If ``attrs`` encounters a field that is set to an `attr.ib` but lacks a type annotation, an `attr.exceptions.UnannotatedAttributeError` is raised. Use ``field_name: typing.Any = attr.ib(...)`` if you don't want to set a type. If you assign a value to those attributes (e.g. ``x: int = 42``), that value becomes the default value like if it were passed using ``attr.ib(default=42)``. Passing an instance of `Factory` also works as expected. Attributes annotated as `typing.ClassVar`, and attributes that are neither annotated nor set to an `attr.ib` are **ignored**. .. _`PEP 526`: https://www.python.org/dev/peps/pep-0526/ :param bool kw_only: Make all attributes keyword-only (Python 3+) in the generated ``__init__`` (if ``init`` is ``False``, this parameter is ignored). :param bool cache_hash: Ensure that the object's hash code is computed only once and stored on the object. If this is set to ``True``, hashing must be either explicitly or implicitly enabled for this class. If the hash code is cached, avoid any reassignments of fields involved in hash code computation or mutations of the objects those fields point to after object creation. If such changes occur, the behavior of the object's hash code is undefined. :param bool auto_exc: If the class subclasses `BaseException` (which implicitly includes any subclass of any exception), the following happens to behave like a well-behaved Python exceptions class: - the values for *eq*, *order*, and *hash* are ignored and the instances compare and hash by the instance's ids (N.B. ``attrs`` will *not* remove existing implementations of ``__hash__`` or the equality methods. It just won't add own ones.), - all attributes that are either passed into ``__init__`` or have a default value are additionally available as a tuple in the ``args`` attribute, - the value of *str* is ignored leaving ``__str__`` to base classes. :param bool collect_by_mro: Setting this to `True` fixes the way ``attrs`` collects attributes from base classes. The default behavior is incorrect in certain cases of multiple inheritance. It should be on by default but is kept off for backward-compatability. See issue `#428 `_ for more details. :param Optional[bool] getstate_setstate: .. note:: This is usually only interesting for slotted classes and you should probably just set *auto_detect* to `True`. If `True`, ``__getstate__`` and ``__setstate__`` are generated and attached to the class. This is necessary for slotted classes to be pickleable. If left `None`, it's `True` by default for slotted classes and ``False`` for dict classes. If *auto_detect* is `True`, and *getstate_setstate* is left `None`, and **either** ``__getstate__`` or ``__setstate__`` is detected directly on the class (i.e. not inherited), it is set to `False` (this is usually what you want). :param on_setattr: A callable that is run whenever the user attempts to set an attribute (either by assignment like ``i.x = 42`` or by using `setattr` like ``setattr(i, "x", 42)``). It receives the same arguments as validators: the instance, the attribute that is being modified, and the new value. If no exception is raised, the attribute is set to the return value of the callable. If a list of callables is passed, they're automatically wrapped in an `attr.setters.pipe`. :param Optional[callable] field_transformer: A function that is called with the original class object and all fields right before ``attrs`` finalizes the class. You can use this, e.g., to automatically add converters or validators to fields based on their types. See `transform-fields` for more details. .. versionadded:: 16.0.0 *slots* .. versionadded:: 16.1.0 *frozen* .. versionadded:: 16.3.0 *str* .. versionadded:: 16.3.0 Support for ``__attrs_post_init__``. .. versionchanged:: 17.1.0 *hash* supports ``None`` as value which is also the default now. .. versionadded:: 17.3.0 *auto_attribs* .. versionchanged:: 18.1.0 If *these* is passed, no attributes are deleted from the class body. .. versionchanged:: 18.1.0 If *these* is ordered, the order is retained. .. versionadded:: 18.2.0 *weakref_slot* .. deprecated:: 18.2.0 ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now raise a `DeprecationWarning` if the classes compared are subclasses of each other. ``__eq`` and ``__ne__`` never tried to compared subclasses to each other. .. versionchanged:: 19.2.0 ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now do not consider subclasses comparable anymore. .. versionadded:: 18.2.0 *kw_only* .. versionadded:: 18.2.0 *cache_hash* .. versionadded:: 19.1.0 *auto_exc* .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01. .. versionadded:: 19.2.0 *eq* and *order* .. versionadded:: 20.1.0 *auto_detect* .. versionadded:: 20.1.0 *collect_by_mro* .. versionadded:: 20.1.0 *getstate_setstate* .. versionadded:: 20.1.0 *on_setattr* .. versionadded:: 20.3.0 *field_transformer* z-auto_detect only works on Python 3 and later.Ncst|dddkrtdp"t|}dko4t|t}oBt|d}|rT|rTtdt||t|dd | |}t|dr| dkr| t|d }|s|dkr| |st| d r| |  dkrdkrt|d rd }n }|dk rB|d k rB|dk rBtd n||d ksf|dkr`|d ksf|rvrtdnH|dks|dkr|dkr|dkr|nrtd|t| dr|nrtd|S)Nrz(attrs only works with new-style classes.Trz/Can't freeze a class with a custom __setattr__.)rrrr)rr)rrr r rFr1zlInvalid value for cache_hash. To use hash caching, hashing must be either explicitly or implicitly enabled.)rzFInvalid value for cache_hash. To use hash caching, init must be True.)r/r?_has_frozen_base_class issubclassrrgr@rrrrrr rrrrr)r is_frozenrZhas_own_setattrZbuilderr;r6rrauto_excrrZeq_rrrhash_r7r:r=Zorder_r4repr_nsrr^rrrr wraps   $   zattrs..wrap)r rr>rCrDrErrF)Z maybe_clsrr$r4r5r6r7rrrr^rr:rr"r;r<rrrr=rr%rr!r r\s 2kcCs"t|jddtjko |jjtjkS)b Check whether *cls* has a frozen ancestor by looking at its __setattr__. r&N)r/rrr&r%rrrr rxs   rcCs |jtkS)r&)rrrrrr rscstfdd|DS)z: Create a tuple of all values of *obj*'s *attrs*. c3s|]}t|jVqdSr)r/rtrobjrr rsz"_attrs_to_tuple..r)r(r\rr'r _attrs_to_tuplesr)cCslt}d}d}d||jt|d|j|}ddt|f|f}tj |||krT|S|d7}d|}qdS)zF Create a "filename" suitable for a function being generated. r+rz r'Nz-{0}) uuiduuid4rOr&r/r%r^ linecachecache setdefault)r func_nameZ unique_idextracountunique_filenameZ cache_linerrr _generate_unique_filenames"   r3c s>tddDd}t|d}t|d}dd|sB|d7}n$tsN|d 7}|d 7}d d 7|gfd d}|r|dt|r|dt|d|dd n|dt|d|dtn |d|d}i} i} t||d} t| | | t |d| d|ft j |<| dS)Ncss0|](}|jdks$|jdkr|jdkr|VqdS)TN)r6r;rrrr rs  z_make_hash..z r6zdef __hash__(selfzhash((z))z):z, *zC, _cache_wrapper=__import__('attr._make')._make._CacheHashWrapper):z_cache_wrapper()csT|||dfgD]}|d|jq$|ddS)z Generate the code for actually computing the hash code. Below this will either be returned directly or used to compute a value which is then cached, depending on the value of cache_hash z %d, self.%s, N)extendrQrt)prefixindentrfr\Zclosing_bracesZ hash_funcZ method_linesZ type_hashrr append_hash_computation_liness  z1_make_hash..append_hash_computation_lineszif self.%s is None:zobject.__setattr__(self, '%s', z self.%s = zreturn self.%szreturn rMrNTr) rEr3r6r rQrrVrUrTr splitlinesr,r-) rr\rrtabr2Zhash_defr;scriptrYlocsbytecoderr:r rsZ       rcCst||ddd|_|S)z% Add a hash method to *cls*. Fr)rrrr\rrr _add_hashsrCcCs dd}|S)z Create __ne__ method. cSs||}|tkrtS| S)zj Check equality and either forward a NotImplemented or return the result negated. )rNotImplemented)r#otherresultrrr rs z_make_ne..__ne__r)rrrr r s rc Csdd|D}t|d}dddg}|rt|ddg}|D](}|d |jf|d |jfq:||d g7}n |d d |}i}i}t||d} t| ||t|d|d|ftj |<|dS)z6 Create __eq__ method for *cls* with *attrs*. cSsg|]}|jr|qSr)r;rrrr r"sz_make_eq..r;zdef __eq__(self, other):z- if other.__class__ is not self.__class__:z return NotImplementedz return (z ) == (r5z other.%s,z )z return TruerMrNNTr) r3rQrtrVrUrTrr=r,r-) rr\r2linesZothersrfr?rYr@rArrr rs2       rcsVddDfddfdd}fdd}fd d }fd d }||||fS) z9 Create ordering methods for *cls* with *attrs*. cSsg|]}|jr|qSr)r<rrrr rLsz_make_order..cs t|S)z& Save us some typing. )r)r'r\rr attrs_to_tupleNsz#_make_order..attrs_to_tuplecs |j|jkr||kStS1 Automatically created by attrs. rrDr#rErIrr rTs z_make_order..__lt__cs |j|jkr||kStSrJrLrMrNrr r]s z_make_order..__le__cs |j|jkr||kStSrJrLrMrNrr r fs z_make_order..__gt__cs |j|jkr||kStSrJrLrMrNrr r os z_make_order..__ge__r)rr\rrr r r)r\rIr r Hs  r cCs&|dkr|j}t|||_t|_|S)z5 Add equality methods to *cls* with *attrs*. N)rprrrrrBrrr _add_eq{s  rOcs$tdd|Dfdd}|S)z^ Make a repr method that includes relevant *attrs*, adding *ns* to the full name. css2|]*}|jdk r|j|jdkr"tn|jfVqdS)FTN)r4rtrrrr rs z_make_repr..c sz tj}Wn tk r*t}|t_YnXt||kr.rror(TFr=r+r4)_already_repring working_setrrvidrr/rsplitr%rxremoverQr7r!rV) r#rSZreal_clsr class_namerFfirstrtZ attr_reprZattr_names_with_reprsrrr r$s6      z_make_repr..__repr__r)r\rr$rrYr rs *rcCs|dkr|j}t|||_|S)z% Add a repr method to *cls*. N)rprr$)rrr\rrr _add_reprs rZcCs8t|stdt|dd}|dkr4tdj|d|S)a Return the tuple of ``attrs`` attributes for a class. The tuple also allows accessing the fields by their names (see below for examples). :param type cls: Class to introspect. :raise TypeError: If *cls* is not a class. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. :rtype: tuple (with name accessors) of `attr.Attribute` .. versionchanged:: 16.2.0 Returned tuple allows accessing the fields by name. Passed object must be a class.rpN({cls!r} is not an attrs-decorated class.r)r r?r/rrOrBrrr fieldss  r]cCsFt|stdt|dd}|dkr4tdj|dtdd|DS)a8 Return an ordered dictionary of ``attrs`` attributes for a class, whose keys are the attribute names. :param type cls: Class to introspect. :raise TypeError: If *cls* is not a class. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. :rtype: an ordered dict where keys are attribute names and values are `attr.Attribute`\ s. This will be a `dict` if it's naturally ordered like on Python 3.6+ or an :class:`~collections.OrderedDict` otherwise. .. versionadded:: 18.1.0 r[rpNr\rcss|]}|j|fVqdSrrrrrr rszfields_dict..)r r?r/rrOrrBrrr fields_dicts  r^cCsDtjdkrdSt|jD]&}|j}|dk r|||t||jqdS)z Validate all attributes on *inst* that have a validator. Leaves all exceptions through. :param inst: Instance of a class with ``attrs`` attributes. FN)rZ_run_validatorsr]rr3r/rt)instrfrrrr validate s  r`cCs d|jkS)Nr)rrrrr _is_slot_clssracCs||kot||S)z> Check if the attribute name comes from a slot class. )ra)Za_namerzrrr _is_slot_attrsrbc  Cs|r|rtd|p|} g} i} |D]j} | js:| jtkr:q$| | | | | j<| jdk rn|dkrhtdd} q$|r~| jtjk st | j|r$d} q$t |d} t | ||||||| | \}}}i}t || d}| t| d| rt|d<t|||t|d|d| ftj| <|d}||_|S)Nz$Frozen classes can't use on_setattr.Tr7rN)r! attr_dictZ_cached_setattrr)r@r7r2r!rQrtr=rrrbr3_attrs_to_init_scriptrUupdaterrTrr=r,r-rh)rr\ post_initrrrrzrhas_global_on_setattrneeds_cached_setattrZfiltered_attrsrcrfr2r?rY annotationsr@rArrrr r%s^           rcCs d||fS)zJ Use the cached object.setattr to set *attr_name* to *value_var*. _setattr('%s', %s)rrLZ value_varhas_on_setattrrrr _setattrnsrmcCsd|t|f|fS)zk Use the cached object.setattr to set *attr_name* to *value_var*, but run its converter first. z_setattr('%s', %s(%s)))_init_converter_patrkrrr _setattr_with_converterus rocCs|rt||dSd||fS)zo Unless *attr_name* has an on_setattr hook, use normal assignment. Otherwise relegate to _setattr. T self.%s = %s)rm)rLrrlrrr _assigns rqcCs$|rt||dSd|t|f|fS)z Unless *attr_name* has an on_setattr hook, use normal assignment after conversion. Otherwise relegate to _setattr_with_converter. Tzself.%s = %s(%s))rornrkrrr _assign_with_converters rrcCs$|dk rd|}nd}d|||fS)z8 Unpack *attr_name* from _kw_only dict. Nz, %sr+z%s = _kw_only.pop('%s'%s)r)rLr2Z arg_defaultrrr _unpack_kw_only_py2s rscCs,dg}|dd|D|dd7}|S)a Unpack all *kw_only_args* from _kw_only dict and handle errors. Given a list of strings "{attr_name}" and "{attr_name}={default}" generates list of lines of code that pop attrs from _kw_only dict and raise TypeError similar to builtin if required attr is missing or extra key is passed. >>> print(" ".join(_unpack_kw_only_lines_py2(["a", "b=42"]))) try: a = _kw_only.pop('a') b = _kw_only.pop('b', 42) except KeyError as _key_error: raise TypeError( ... if _kw_only: raise TypeError( ... ztry:css |]}dt|dVqdS)r6rQN)rssplit)rargrrr rsz,_unpack_kw_only_lines_py2..a except KeyError as _key_error: raise TypeError( '__init__() missing required keyword-only argument: %s' % _key_error ) if _kw_only: raise TypeError( '__init__() got an unexpected keyword argument %r' % next(iter(_kw_only)) ) rM)r7rt) kw_only_argsrGrrr _unpack_kw_only_lines_py2s   rwc sg} |r| d|dkrP|dkr,t} t} qX| dfdd} fdd} nt} t} g} g} g}i}dd i}|D]L}|jr|||j}|jd k p|jtj k o|}|j d }t |j t }|r|j jrd }nd }|jd kr|r`t|j}|jd k r6| | ||d|f|t|jf}|j||<n| | ||d|f||j j||<nT|jd k r| | |d|f|t|jf}|j||<n| | |d|f|n|j tk r<|s.fmt_settercs.|st|rt|||Sd|t|f|fS)Nz_inst_dict['%s'] = %s(%s))rbrornrkryrr fmt_setter_with_convertersz8_attrs_to_init_script..fmt_setter_with_converterreturnN_r#r+Fz(%s)zattr_dict['%s'].defaultz%s=attr_dict['%s'].defaultz %s=NOTHINGzif %s is not NOTHING:r6zelse:rPr4rz#if _config._run_validators is True:Z__attr_validator_Z__attr_z %s(self, %s, self.%s)zself.__attrs_post_init__()rjrxrpNone,css|]}|jrd|jVqdS)zself.N)r7rtrrrr rsz(_attrs_to_init_script..z BaseException.__init__(self, %s)rz %s**_kw_onlyz%s*, %sz(def __init__(self, {args}): {lines} z pass)argsrG)rQrmrorqrrr3rtr=rrlstriprCr2rB takes_selfr7_init_factory_patrOr8rnrIr!r:r0rrrVr rw)r\rrrfrrzrrhrgrGrzr{rrvZattrs_to_validateZnames_for_globalsrirfrLrlZarg_nameZ has_factoryZ maybe_selfZinit_factory_nameZ conv_nameruZval_nameZinit_hash_cachevalsrryr rdsz                                              rdc@s`eZdZdZdZdddZddZedd d Ze d d Z d dZ ddZ ddZ ddZdS)raH *Read-only* representation of an attribute. Instances of this class are frequently used for introspection purposes like: - `fields` returns a tuple of them. - Validators get them passed as the first argument. - The *field transformer* hook receives a list of them. :attribute name: The name of the attribute. :attribute inherited: Whether or not that attribute has been inherited from a base class. Plus *all* arguments of `attr.ib` (except for ``factory`` which is only syntactic sugar for ``default=Factory(...)``. .. versionadded:: 20.1.0 *inherited* .. versionadded:: 20.1.0 *on_setattr* .. versionchanged:: 20.2.0 *inherited* is not taken into account for equality checks and hashing anymore. For the full version history of the fields, see `attr.ib`. )rtr2r3r4r;r<r6r7r9r0r8r:rrr=NFcCst|| |d\} }t|t}|d||d||d||d||d| |d||d||d ||d | |d | rt| nt|d | |d | |d||d|dS)NTrtr2r3r4r;r<r6r7r8r9r0r:rrr=)r>rrrr _empty_metadata_singleton)r#rtr2r3r4r5r6r7rrr9r0r8r:r;r<r= bound_setattrrrr r s*              zAttribute.__init__cCs tdSrrrrrr r@ szAttribute.__setattr__c sV|dkrj}njdk r"tdfddtjD}|f|jj|ddd|S)Nz8Type annotation and type argument cannot both be presentcs i|]}|dkr|t|qS))rtr3r2r0rrr)rrrrr rL s z0Attribute.from_counting_attr..F)rtr3r2r0r5rr)r0r@rr _validator_default)rrtrr0 inst_dictrrr rC s&   zAttribute.from_counting_attrcCstjttdd|jo|jS)zD Simulate the presence of a cmp attribute and warn. r<r)rrrrr;r<r"rrr r5b sz Attribute.cmpcKst|}|||S)z Copy *self* and apply *changes*. This works similarly to `attr.evolve` but that function does not work with ``Attribute``. It is mainly meant to be used for `transform-fields`. .. versionadded:: 20.3.0 )copy _setattrsr)r#changesnewrrr rul s zAttribute.evolvecstfddjDS)( Play nice with pickle. c3s*|]"}|dkrt|ntjVqdS)r9N)r/rr9rr"rr r sz)Attribute.__getstate__..)rErr"rr"r r~ s zAttribute.__getstate__cCs|t|j|dS)rN)rrr)r#rrrr r szAttribute.__setstate__cCsHt|t}|D]2\}}|dkr,|||q|||r)rkrr4r;r<r6r7r=r9NTFrrcCsbtjd7_tj|_||_||_||_||_| |_| |_||_ ||_ ||_ | |_ | |_ | |_dSr)rH cls_counterrkrrr8r4r;r<r6r7r9r0r:r=)r#r2r3r4r5r6r7r8r9r0r:r;r<r=rrr r sz_CountingAttr.__init__cCs$|jdkr||_nt|j||_|S)z Decorator that adds *meth* to the list of validators. Returns *meth* unchanged. .. versionadded:: 17.1.0 N)rrGr#rrrr r3 s z_CountingAttr.validatorcCs"|jtk rtt|dd|_|S)z Decorator that allows to set the default for an attribute. Returns *meth* unchanged. :raises DefaultAlreadySetError: If default has been set before. .. versionadded:: 17.1.0 T)r)rr!rrBrrrr r2$ s z_CountingAttr.default) r%r&r'r(rrErrprrr3r2rrrr rH s2)rH)rr7r6c@s&eZdZdZeZeZdddZdS)rBa Stores a factory callable. If passed as the default value to `attr.ib`, the factory is used to generate a new value. :param callable factory: A callable that takes either none or exactly one mandatory positional argument depending on *takes_self*. :param bool takes_self: Pass the partially initialized instance that is being initialized as a positional argument. .. versionadded:: 17.1.0 *takes_self* FcCs||_||_dS)z `Factory` is part of the default machinery so if we want a default value here, we have to implement it ourselves. N)rIr)r#rIrrrr rL szFactory.__init__N)F)r%r&r'r(rJrIrrrrrr rB9 srBc Kst|tr|}n*t|ttfr2tdd|D}ntd|dd}t|||dkrXind|i}ztdj dd|_ Wnt t fk rYnX|d d}t|| d | d d \|d <|d <tfd |i||S)aB A quick way to create a new class called *name* with *attrs*. :param str name: The name for the new class. :param attrs: A list of names or a dictionary of mappings of names to attributes. If *attrs* is a list or an ordered dict (`dict` on Python 3.6+, `collections.OrderedDict` otherwise), the order is deduced from the order of the names or attributes inside *attrs*. Otherwise the order of the definition of the attributes is used. :type attrs: `list` or `dict` :param tuple bases: Classes that the new class will subclass. :param attributes_arguments: Passed unmodified to `attr.s`. :return: A new class with *attrs*. :rtype: type .. versionadded:: 17.1.0 *bases* .. versionchanged:: 18.1.0 If *attrs* is ordered, the order is retained. css|]}|tfVqdSr)rJrrrr rq szmake_class..z(attrs argument must be a dict or a list.rNrr%__main__r5r;r<Tr)rCrrDrEr?popr0sys _getframe f_globalsrr&rr@r>r)rtr\basesZattributes_argumentsZcls_dictrftype_r5rrr make_classU s:      r)rr6c@seZdZdZeZddZdS) _AndValidatorz2 Compose many validators to a single one. cCs|jD]}||||qdSr) _validators)r#r_rdrrrrr __call__ s z_AndValidator.__call__N)r%r&r'r(rJrrrrrr r srcGs6g}|D] }|t|tr |jn|gqtt|S)z A validator that composes multiple validators into one. When called on a value, it runs all wrapped validators. :param callables validators: Arbitrary number of validators. .. versionadded:: 17.1.0 )r7rCrrrE)Z validatorsrr3rrr rG s rGcsfdd}|S)z A converter that composes multiple converters into one. When called on a value, it runs all wrapped converters, returning the *last* value. :param callables converters: Arbitrary number of converters. .. versionadded:: 20.1.0 csD] }||}q|Srr)rr8 convertersrr pipe_converter s zpipe..pipe_converterr)rrrrr rF s rF)T)NNNNNNNFFTFFFFFNNFFNNN)N)NN)N)` __future__rrrrr,r threadingr*roperatorrr+rrZ_compatr r r r r rr exceptionsrrrrrrrrrnrrRr`rrrbrr!intr*rJrZr[rargrirnr}r~rrrrrr>rr\rrr)r3rrCrrr rOlocalrRrrZr]r^r`rarbrrmrorqrrrsrwrdrrZ_arHrBrrrGrFrrrr s  $   2   k   | P*3 ; I   )6       D