U afWe@sddlmZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl mZddlmZmZmZddlmZmZmZmZmZmZddlmZmZmZmZejZ dZ!d Z"d Z#e $iZ%eZ&e'ej(ej)Z*Gd d d ej+Z,e,j-Z-Gd dde.Z/e-ddddddddddddddfddZ0dddZ1dddZ2ddZ3e3ddddgZ4ddZ5d d!Z6d"d#Z7d$d%Z8d&d'Z9d(d)Z:d*d+Z;d,d-Zd2d3Z?dd4d5Z@dd6dZAeAZBd7d8ZCd9d:ZDd;d<ZEd=d>ZFd?d@ZGdAdBZHdCdDZIddEdFZJdGdHZKddIdJZLdKdLZMdMdNZNdOdPZ)dQdRZOdSdTZPdUdUdVdUdWdXdYZQdUdUdVdZdUd[d\d]ZRdUdUdVdUd^d_d`ZSdUdUdVdZdUd[dadbZTdVdVdcdddedfZUdgdVdVdVdVdVdVdcdVdVdVdUdhdi djdkZVdUdUdldmdnZWGdodpdpZXdqdreXjYDZZeFeJeLeXeZdsdtdreZDdsdudreZDdsZXGdvdwdwZ[eJeLe[Z[GdxdydyZ\dzdre\jYDZ]eFeJeLe\e]dse]dse]dsZ\Gd{dZdZZ^d|drd}DZ]eFeJeLe^e]dse]dse]dsZ^efdfd~dZ_eAdddGdddZ`ddZaddZ'dS)) annotationsN) itemgetter)_compat_configsetters) PY_3_8_PLUS PY_3_10_PLUS PY_3_11_PLUS_AnnotationExtractor_get_annotationsget_generic_base)DefaultAlreadySetErrorFrozenInstanceErrorNotAnAttrsClassErrorUnannotatedAttributeErrorz__attr_factory_%s)ztyping.ClassVarz t.ClassVarClassVarztyping_extensions.ClassVarZ_attrs_cached_hashc@s(eZdZdZeZddZddZdS)_NothingaF Sentinel to indicate the lack of a value when `None` is ambiguous. If extending attrs, you can use ``typing.Literal[NOTHING]`` to show that a value may be ``NOTHING``. .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False. .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant. cCsdS)NNOTHINGselfrr;/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/attr/_make.py__repr__Isz_Nothing.__repr__cCsdS)NFrrrrr__bool__Lsz_Nothing.__bool__N) __name__ __module__ __qualname____doc__enumautorrrrrrrr<s rc@s"eZdZdZeddfddZdS)_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. NrcCs||fSNr)rZ_none_constructor_argsrrr __reduce__bsz_CacheHashWrapper.__reduce__)rrrrtyper$rrrrr!Vs r!TFcCst|| | d\} }} }|dk r:|dk r:|dk r:d}t|| dk rr|tk rVd}t|t| sjd}t|t| }|dkr~i}t| ttfrt j | } |rt|ttfrt |}|rt|ttfrt |}t |||d|||||| | || || |dS)a Create a new field / attribute on a class. Identical to `attrs.field`, except it's not keyword-only. Consider using `attrs.field` in new code (``attr.ib`` will *never* go away, though). .. warning:: Does **nothing** unless the class is also decorated with `attr.s` (or similar)! .. 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 .. versionchanged:: 21.1.0 *eq*, *order*, and *cmp* also accept a custom callable .. versionchanged:: 21.1.0 *cmp* undeprecated .. versionadded:: 22.2.0 *alias* 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 convertermetadatar%kw_onlyeqeq_keyorder order_key on_setattralias) _determine_attrib_eq_order TypeErrorr ValueErrorcallableFactory isinstancelisttuplerpipeand_ _CountingAttr)r'r(r)r*r+r,r.r%r-factoryr/r0r2r4r5r1r3msgrrrattribfsX7  rCcCst||d}t|||dS)z[ Evaluate the script with the given global (globs) and local (locs) variables. execN)compileeval)scriptglobslocsfilenamebytecoderrr_compile_and_evals rMc Cs~|dkr in|}d}|}t|d|d|f}tj||} | |krFqh|ddd|d}|d7}qt||||||S)zO Create the method with the script given and return the method object. NrT->)len splitlines linecachecache setdefaultrM) namerHrKrIlocalsrJcount base_filenameZlinecache_tupleZold_valrrr _make_methods rZcCsv|d}d|ddg}|rJt|D] \}}|d|d|dq&n |dttd }td ||||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 z(tuple):z __slots__ = () z% = _attrs_property(_attrs_itemgetter())z pass)Z_attrs_itemgetterZ_attrs_property ) enumerateappendrpropertyrMjoin)Zcls_name attr_namesZattr_class_nameZattr_class_templatei attr_namerIrrr_make_attr_tuple_classs    re _Attributesattrs base_attrsZbase_attrs_mapcCs2t|}|dr(|dr(|dd}|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. )'"rrN)str startswithendswith_CLASSVAR_PREFIXES)Zannotrrr _is_class_var!s rocCs ||jkS)zR Check whether *cls* defines *attrib_name* (and doesn't just inherit it). )__dict__)clsZ attrib_namerrr_has_own_attribute2srrcCsg}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*. rrN__attrs_attrs__T inheritedr) reversed__mro__getattrrurVevolver_setinsertadd)rqtaken_attr_namesrh base_attr_mapbase_clsafilteredseenrrr_collect_base_attrs9s"     rcCsng}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. rrNrsTrt)rwrxrVryr|r_)rqr}rhr~rrrrr_collect_base_attrs_brokenXs     rc s"|jt||dk r$t|}n|dkrddD}g}t}D]X\} } t| rbqP|| | t} t | t s| tkrt nt | d} | | | fqP||} t | dkrtddt| fd d d d ntd dDdd d }fdd|D} |r6t|dd| D\}}nt|dd| D\}}|rpdd| D} dd|D}|| }d}dd|DD]H} |dkr| jtkrd| }t||dkr| jtk rd}q|dk r|||}dd|D}dd|D}t|j|}t||||fS)a3 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. If *collect_by_mro* is True, collect them in the correct MRO order, otherwise use the old -- incorrect -- order. See #428. Return an `_Attributes`. NTcSsh|]\}}t|tr|qSrr;r@.0rVattrrrr s z#_transform_attrs..r'rz1The following `attr.ib`s lack a type annotation: , cs |jSr")getcounter)n)cdrrz"_transform_attrs..)key.css$|]\}}t|tr||fVqdSr"rrrrr s z#_transform_attrs..cSs |djSNr)r)errrrrcs&g|]\}}tj|||dqS))rVcar%) Attributefrom_counting_attrr)rrdr)annsrr s z$_transform_attrs..cSsh|] }|jqSrrVrrrrrrscSsh|] }|jqSrrrrrrrscSsg|]}|jddqST)r/ryrrrrrscSsg|]}|jddqSrrrrrrrsFcss&|]}|jdk r|jdkr|VqdS)FN)r,r/rrrrrs zlNo mandatory attributes allowed after an attribute with a default value or factory. Attribute in question: cSs(g|] }|js |jt|jdn|qS))r5)r5ry_default_init_alias_forrVrrrrrscSsg|] }|jqSrrrrrrrs)rpr r<itemsrzror|rrr;r@rCr_rQrrasortedrrr'r8rerrf)rqthese auto_attribsr/collect_by_mrofield_transformerZca_listZca_namesZ annot_namesrdr%rZ unannotatedZ own_attrsrhr~rgZ had_defaultrBrbZ AttrsClassr)rrr_transform_attrsts            rc Csddddddddd g }|dk r*|d n|d d d dddddg|ddgt|d}|tj|d}tdd|||d|idS)Nzdef wrapper(_cls):z __class__ = _clsz def __getattr__(self, item, cached_properties=cached_properties, original_getattr=original_getattr, _cached_setattr_get=_cached_setattr_get):z+ func = cached_properties.get(item)z if func is not None:z! result = func(self)z1 _setter = _cached_setattr_get(self)z# _setter(item, result)z return resultz, return original_getattr(self, item)z try:z2 return super().__getattribute__(item)z except AttributeError:z4 if not hasattr(super(), '__getattr__'):z raisez- return super().__getattr__(item)zY original_error = f"'{self.__class__.__name__}' object has no attribute '{item}'"z- raise AttributeError(original_error)z return __getattr__z__getattr__ = wrapper(_cls)rx)cached_properties_cached_setattr_getoriginal_getattr __getattr__r]_cls)rW)r_extend_generate_unique_filename _OBJ_SETATTR__get__rZra)rrrqlinesunique_filenameglobrrr_make_cached_property_getattrsX   rcCs.t|tr$|dkr$t|||dStdS)z4 Attached to frozen classes as __setattr__. ) __cause__ __context__ __traceback__N)r; BaseException __setattr__rrrVvaluerrr_frozen_setattrssrcCs tdS)z4 Attached to frozen classes as __delattr__. Nr)rrVrrr_frozen_delattrs*src@seZdZdZdZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZddZddZddZddZdd Zd!d"Zd#d$Zd%S)& _ClassBuilderz( Iteratively build *one* class. ) _attr_names_attrs_base_attr_map _base_names _cache_hashr _cls_dict_delete_attribs_frozen _has_pre_init_pre_init_has_args_has_post_init_is_exc _on_setattr_slots _weakref_slot_wrote_own_setattr_has_custom_setattrcCst||||| |\}}}||_|r,t|jni|_||_dd|D|_||_tdd|D|_ ||_ ||_ ||_ | |_ tt|dd|_d|_|jr|j}t|}t|jdk|_tt|dd|_t| |_| |_| |_| |_d|_|j|jd <|rt|jd <t|jd <d |_n| tt j!t j"fkrd}}|D]8}|j#dk rPd }|j$dk r`d }|r<|r<qvq<| tkr|s|r| t j!kr|r| t j"kr|sd|_|r|%\|jd <|jd<dS)NcSsh|] }|jqSrrrrrrrhsz)_ClassBuilder.__init__..css|] }|jVqdSr"rrrrrrjsz)_ClassBuilder.__init__..__attrs_pre_init__Fr__attrs_post_init__rsr __delattr__T __getstate__ __setstate__)&rrdictrprrrrr=rrrrrboolrxrrrinspect signaturerQ parametersrrrrrrrr_DEFAULT_ON_SETATTRrvalidateconvertr(r-_make_getstate_setstate)rrqrslotsfrozen weakref_slotgetstate_setstaterr/ cache_hashis_excrr4Zhas_custom_setattrrrgrhZbase_mapZ pre_init_funcZpre_init_signatureZ has_validatorZ has_converterrrrr__init__Ks           z_ClassBuilder.__init__cCsd|jjdS)Nz<_ClassBuilder(cls=z)>)rrrrrrrsz_ClassBuilder.__repr__cCsL|jdkr|}n|}tr*t|}t|ddrHd|jkrH||S)z Finalize class based on the accumulated configuration. Builder cannot be used after calling this method. T__attrs_init_subclass__N) r_create_slots_class_patch_original_classr abcZupdate_abstractmethodsrxrpr)rrqrrr build_classs    z_ClassBuilder.build_classc Cs|j}|j}|jrV|jD]<}||krt||ttk rttt ||W5QRXq|j D]\}}t |||q`|j st|ddrd|_|jst|_|S)zA Apply accumulated methods and return the class. __attrs_own_setattr__F)rrrrrx _SENTINEL contextlibsuppressAttributeErrordelattrrrsetattrrrrrr)rrq base_namesrVrrrrrs*  z#_ClassBuilder._patch_original_classc sfddjD}jsTd|d<jsTjjD]jddr4t|d<qTq4i}d}jj ddD]:jdd d k rd }| fd dt d gDqlt j j}jrdt jd d krd|kr|s|d7}trdd|D}ni}g}|rtj}|D]F\}} ||f7}||=|| t| j} | tjjk r| ||<q|d} | d k r|| t|| j|d<fdd|Dfdd|DfddD| jrtt|d <jj|d<tjjjjj|} t | j!|D]} t"| t#t$frRt | j%dd }n(t"| t&rnt | j'dd }n t | dd }|sq.|D]:}z|j(jk}Wnt)k rYnX|r| |_(qq.| S)zL Build and return a new class with a `__slots__` attribute. cs(i|] \}}|tjdkr||qS)rp __weakref__)rpr)r=rrkvrrr sz5_ClassBuilder._create_slots_class..FrrrrNrNTcsi|]}|t|qSrrxrrV)rrrrs __slots__r)rcSs$i|]\}}t|tjr||jqSr)r; functoolscached_propertyfunc)rrVrrrrrs rcsg|]}|kr|qSrrr)rrrr=sz5_ClassBuilder._create_slots_class..csi|]\}}|kr||qSrr)rZslotZslot_descriptor) slot_namesrrrCscsg|]}|kr|qSrrr) reused_slotsrrrHsr __closure__)*rrrrr __bases__rprrrwupdaterxrzrrrrr r_rrreturn_annotation Parameteremptyrr_HASH_CACHE_FIELDr=rr%r itertoolschainvaluesr; classmethod staticmethod__func__r`fget cell_contentsr8)rrZexisting_slotsZweakref_inheritednamesrZ&additional_closure_functions_to_updateZclass_annotationsrVr annotationrrqitemZ closure_cellscellmatchr)rrrrrrrs                    z!_ClassBuilder._create_slots_classcCs |t|j||j|jd<|S)Nr)_add_method_dunders _make_reprrrr)rnsrrradd_reprus z_ClassBuilder.add_reprcCs<|jd}|dkr d}t|dd}|||jd<|S)Nrz3__str__ can only be generated if a __repr__ exists.cSs|Sr"rrrrr__str__sz&_ClassBuilder.add_str..__str__r)rrr8r)rr)rBrrrradd_str{s z_ClassBuilder.add_strcs<tdd|jDfdd}|jfdd}||fS)zF Create custom __setstate__ and __getstate__ methods. css|]}|dkr|VqdS)rNr)rZanrrrrsz8_ClassBuilder._make_getstate_setstate..csfddDS)9 Automatically created by attrs. csi|]}|t|qSrrrrrrrszQ_ClassBuilder._make_getstate_setstate..slots_getstate..rr)state_attr_namesrrslots_getstatesz=_ClassBuilder._make_getstate_setstate..slots_getstatecsft|}t|tr4t|D]\}}|||qn D]}||kr8||||q8rb|tddS)rN)rrr;r=zipr)rstateZ_ClassBuilder__bound_setattrrVrZhash_caching_enabledrrrslots_setstates  z=_ClassBuilder._make_getstate_setstate..slots_setstate)r=rr)rrr!rr rrs z%_ClassBuilder._make_getstate_setstatecCsd|jd<|S)N__hash__)rrrrrmake_unhashables z_ClassBuilder.make_unhashablecCs(|t|j|j|j|jd|jd<|S)Nrrr")r _make_hashrrrrrrrrradd_hashs z_ClassBuilder.add_hashcCsF|t|j|j|j|j|j|j|j|j |j |j |j dd |j d<|S)NF attrs_initrr _make_initrrrrrrrrrrrrrrrradd_inits" z_ClassBuilder.add_initcCstdd|jD|jd<dS)Ncss |]}|jr|js|jVqdSr")r,r/rV)rfieldrrrrsz/_ClassBuilder.add_match_args..__match_args__)r=rrrrrradd_match_argssz_ClassBuilder.add_match_argscCsF|t|j|j|j|j|j|j|j|j |j |j |j dd |j d<|S)NTr'__attrs_init__r)rrrradd_attrs_inits" z_ClassBuilder.add_attrs_initcCs2|j}|t|j|j|d<|t|d<|S)N__eq____ne__)rr_make_eqrr_make_nerrrrradd_eqs  z_ClassBuilder.add_eqcs>j}fddtjjD\|d<|d<|d<|d<S)Nc3s|]}|VqdSr")r)rmethrrrrsz*_ClassBuilder.add_order..__lt____le____gt____ge__)r _make_orderrrr5rrr add_orders   z_ClassBuilder.add_ordercs|jr |Si|jD],}|jp"|j}|r|tjk r||f|j<qsJ|S|jr\d}t|fdd}d|j d<| ||j d<d|_ |S)Nz7Can't combine custom __setattr__ with on_setattr hooks.csFz|\}}Wntk r(|}YnX||||}t|||dSr")KeyErrorr)rrVvalrhookZnvalZsa_attrsrrrs   z._ClassBuilder.add_setattr..__setattr__Trr) rrr4rrNO_OPrVrr8rrr)rrr4rBrrrAr add_setattrs"   z_ClassBuilder.add_setattrc Csxtt|jj|_W5QRXtt|jjd|j|_W5QRXttd|jjd|_W5QRX|S)zL Add __module__ and __qualname__ to a *method* if possible. rz$Method generated by attrs for class )rrrrrrrr)rmethodrrrr&s    z!_ClassBuilder._add_method_dundersN)rrrrrrrrrrrrrr#r&r+r.r0r6r=rCrrrrrr1s(\$ )   #rcCst|dk r(t|dk |dk fr(d}t||dk r8||fS|dkrD|}|dkrP|}|dkrl|dkrld}t|||fS) 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*. N&Don't mix `cmp` with `eq' and `order`.FT-`order` can only be True if `eq` is True too.anyr8)r*r0r2 default_eqrBrrr_determine_attrs_eq_order9srKc Cs|dk r(t|dk |dk fr(d}t|dd}|dk rP||\}}||||fS|dkrd|d}}n ||\}}|dkr||}}n ||\}}|dkr|dkrd}t|||||fS)rENrFcSs t|rd|}}nd}||fS)z8 Decide whether a key function is used. TN)r9)rrrrrdecide_callable_or_boolean^s z>_determine_attrib_eq_order..decide_callable_or_booleanFTrGrH) r*r0r2rJrBrLZcmp_keyr1r3rrrr6Us"       r6cCsF|dks|dkr|S|dkr(|dkr(|S|D]}t||r,dSq,|S)ap 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. TFN)rr)rqflag auto_detectZdundersr'Zdunderrrr_determine_whether_to_implements  rOcsdk r"ddl}|jtdddt|||d\|dk r@| t ttfrXtj  fdd}|dkr|S||S)a A class decorator that adds :term:`dunder methods` according to the specified attributes using `attr.ib` or the *these* argument. Consider using `attrs.define` / `attrs.frozen` in new code (``attr.s`` will *never* go away, though). Args: repr_ns (str): When using nested classes, there was no way in Python 2 to automatically detect that. This argument allows to set a custom name for a more meaningful ``repr`` output. This argument is pointless in Python 3 and is therefore deprecated. .. caution:: Refer to `attrs.define` for the rest of the parameters, but note that they can have different defaults. Notably, leaving *on_setattr* as `None` will **not** add any hooks. .. 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* .. versionchanged:: 21.1.0 ``init=False`` injects ``__attrs_init__`` .. versionchanged:: 21.1.0 Support for ``__attrs_pre_init__`` .. versionchanged:: 21.1.0 *cmp* undeprecated .. versionadded:: 21.3.0 *match_args* .. versionadded:: 22.2.0 *unsafe_hash* as an alias for *hash* (for :pep:`681` compliance). .. deprecated:: 24.1.0 *repr_ns* .. versionchanged:: 24.1.0 Instances are not compared as tuples of attributes anymore, but using a big ``and`` condition. This is faster and has more correct behavior for uncomparable values like `math.nan`. .. versionadded:: 24.1.0 If a class has an *inherited* classmethod called ``__attrs_init_subclass__``, it is executed after the class is created. .. deprecated:: 24.1.0 *hash* is deprecated in favor of *unsafe_hash*. NrzQThe `repr_ns` argument is deprecated and will be removed in or after August 2025.) stacklevelcsp t|}dkot|t}o*t|d}|r@|r@d}t|t||t|dd | |}t|dr|dkr|t|d}|s|dkr| |st|dr| |  dkrdkrt|d rd dk r$ d k r$ dk r$d }t | d ksH dkrB|d ksH|r\rd }t |nL dks dkr|dkr|dkr| nrd }t ||t| d r|n|rd}t |tr rt|ds||S)NTrz/Can't freeze a class with a custom __setattr__.)rrrr)r1r2)r8r9r:r;r"Fr&zlInvalid 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-)_has_frozen_base_class issubclassrrrr8rrOrrr6r=rCr7r&r#r+r0r r.r)rq is_frozenrZhas_own_setattrrBZbuilderr0rrNauto_excrrZeq_rrrr+r,r/ match_argsr4Zorder_r)repr_nsrrkrrrrwrap s   $    zattrs..wrap) warningswarnDeprecationWarningrKr;r<r=rr>)Z maybe_clsrrYr)r*r+r,rrrrkrr/rrWr0r2rNrrr4rrX unsafe_hashr[rZrrVrrgs"\ 4hcCs |jtkS)zV Check whether *cls* has a frozen ancestor by looking at its __setattr__. )rr)rqrrrrS~srSc Cs$d|d|jdt|d|jdS)zF Create a "filename" suitable for a function being generated. z. r+zdef __hash__(selfzhash((r\z):z, *zC, _cache_wrapper=__import__('attr._make')._make._CacheHashWrapper):z_cache_wrapper()c s|||ddgD]Z}|jrhd|jd}|j|<|d|d|jdq&|d|jdq&|dd S) 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 ra,__key(self.z), self.r[N)rr1rVr_)prefixindentrcmp_namergZclosing_bracesrIZ hash_funcZ method_linesZ type_hashrrappend_hash_computation_liness  z1_make_hash..append_hash_computation_lineszif self.z is None:zobject.__setattr__(self, '', rPself. = z return self.zreturn r]r")r=rr+r_rrarZ) rqrgrrtabrZhash_defrlrHrrkrr%sD      r%cCst||ddd|_|S)z% Add a hash method to *cls*. Fr$)r%r"rqrgrrr _add_hashsrrcCs dd}|S)z Create __ne__ method. cSs||}|tkrtS| S)zj Check equality and either forward a NotImplemented or return the result negated. )r1NotImplemented)rotherresultrrrr2s z_make_ne..__ne__r)r2rrrr4s r4c Csdd|D}t|d}dddg}i}|r|d|D]}|jrd|jd }|j||<|d |d |jd |d |jd n|d|jd|j||dk r8|dd|d<q8|dn |dd|}td|||S)z6 Create __eq__ method for *cls* with *attrs*. cSsg|]}|jr|qSr)r0rrrrrsz_make_eq..r0zdef __eq__(self, other):z- if other.__class__ is not self.__class__:z return NotImplementedz return (rdrerarfz) == z(other.rbrgz == other.rNz andz )z return Truer]r1)rr_r1rVrarZ)rqrgrrrIrrjrHrrrr3s.        r3csVddDfddfdd}fdd}fd d }fd d }||||fS) z9 Create ordering methods for *cls* with *attrs*. cSsg|]}|jr|qSr)r2rrrrrsz_make_order..cs tddfddDDS)z& Save us some typing. css"|]\}}|r||n|VqdSr"r)rrrrrrr$sz6_make_order..attrs_to_tuple..c3s |]}t|j|jfVqdSr")rxrVr3robjrrr&s)r=rvrgrvrattrs_to_tuple s  z#_make_order..attrs_to_tuplecs |j|jkr||kStSz1 Automatically created by attrs.  __class__rsrrtryrrr8+s z_make_order..__lt__cs |j|jkr||kStSrzr{r}r~rrr94s z_make_order..__le__cs |j|jkr||kStSrzr{r}r~rrr:=s z_make_order..__gt__cs |j|jkr||kStSrzr{r}r~rrr;Fs z_make_order..__ge__r)rqrgr8r9r:r;r)rgryrr<s r<cCs&|dkr|j}t|||_t|_|S)z5 Add equality methods to *cls* with *attrs*. N)rsr3r1r4r2rqrrr_add_eqRs  rcCst|d}tdd|D}dd|D}t|d<t|d<t|d<g}|D]N\}}} | r`d |n d |d } |tkrd || fn d ||| f} || qJd|} |dkrd} n|d} ddddddddddddd| d| ddd g}td!d"|||d#S)$Nr)css6|].}|jdk r|j|jdkr"tn|j|jfVqdS)FTN)r)rVr,rrrrrds z_make_repr..cSs$i|]\}}}|tkr|d|qS)_repr)r))rrVrrdrrrrisz_make_repr..rrrrnzgetattr(self, "z ", NOTHING)z %s={%s!r}z%s={%s_repr(%s)}rz1{self.__class__.__qualname__.rsplit(">.", 1)[-1]}z.{self.__class__.__name__}zdef __repr__(self):z try:z: already_repring = _compat.repr_context.already_repringz except AttributeError:z! already_repring = {id(self),}z: _compat.repr_context.already_repring = already_repringz else:z# if id(self) in already_repring:z return '...'z else:z# already_repring.add(id(self))z return f'(z)'z finally:z$ already_repring.remove(id(self))rr])rI) rr=rrrr)r_rarZ)rgrrqrZattr_names_with_reprsrIZattribute_fragmentsrVrrcaccessorfragmentZ repr_fragmentZcls_name_fragmentrrrrr_sZ    rcCs |dkr|j}t||||_|S)z% Add a repr method to *cls*. N)rsrr)rqrrgrrr _add_reprsrcCsvt|}|dkr&t|ts&d}t|t|dd}|dkrr|dk r`t|dd}|dk r`||_|S|d}t||S)aG Return the tuple of *attrs* attributes for a class. The tuple also allows accessing the fields by their names (see below for examples). Args: cls (type): Class to introspect. Raises: TypeError: If *cls* is not a class. attrs.exceptions.NotAnAttrsClassError: If *cls* is not an *attrs* class. Returns: tuple (with name accessors) of `attrs.Attribute` .. versionchanged:: 16.2.0 Returned tuple allows accessing the fields by name. .. versionchanged:: 23.1.0 Add support for generic classes. NPassed object must be a class.rs! is not an attrs-decorated class.)r r;r%r7rxrsr)rqZ generic_baserBrgrrrfieldss   rcCsJt|tsd}t|t|dd}|dkr<|d}t|dd|DS)a Return an ordered dictionary of *attrs* attributes for a class, whose keys are the attribute names. Args: cls (type): Class to introspect. Raises: TypeError: If *cls* is not a class. attrs.exceptions.NotAnAttrsClassError: If *cls* is not an *attrs* class. Returns: dict[str, attrs.Attribute]: Dict of attribute name to definition .. versionadded:: 18.1.0 rrsNrcSsi|] }|j|qSrrrrrrrszfields_dict..)r;r%r7rxr)rqrBrgrrr fields_dicts   rcCsDtjdkrdSt|jD]&}|j}|dk r|||t||jqdS)z Validate all attributes on *inst* that have a validator. Leaves all exceptions through. Args: inst: Instance of a class with *attrs* attributes. FN)rZ_run_validatorsrr|r(rxrV)instrrrrrrs rcCs||}|od|jkS)z> Check if the attribute name comes from a slot class. r)rrp)Za_namer~rqrrr _is_slot_attrs rc  Cs6| dk o| tjk } |r&| r&d} t| |p,|}g}i}|D]b}|jsP|jtkrPq:|||||j<|jdk r|dkrd} t| d}q:| r:|jtjk r:d}q:t |d}t ||||||||| || | rdnd \}}}|j t j kr|t j |j j|t|d|rtj|d<t| r dnd|||}||_|S)Nz$Frozen classes can't use on_setattr.Tr,r/r)r attr_dictr)rrBr8r,r'rr_rVr4r_attrs_to_init_scriptrsysmodulesrrprrrZ__annotations__)rqrgpre_initpre_init_has_args post_initrrrr~rZcls_on_setattrr(has_cls_on_setattrrBneeds_cached_setattrZfiltered_attrsrrrrHrIrr,rrrr*s`        r*rkrrd value_varhas_on_setattrreturncCsd|d|dS)zJ Use the cached object.setattr to set *attr_name* to *value_var*. _setattr('rmrbrrdrrrrr_setattrWsr Converterrdrrr-rcCsd|d|||dS)zk Use the cached object.setattr to set *attr_name* to *value_var*, but run its converter first. rrmrb)_fmt_converter_callrdrrr-rrr_setattr_with_converter^sr)rdrrrcCs |rt||dSd|d|S)zo Unless *attr_name* has an on_setattr hook, use normal assignment. Otherwise relegate to _setattr. Trnro)r)rdrrrrr_assignhs rcCs*|rt||d|Sd|d|||S)z Unless *attr_name* has an on_setattr hook, use normal assignment after conversion. Otherwise relegate to _setattr_with_converter. Trnro)rrrrrr_assign_with_converterssrzdict[str, type])rrr~cs`|dkrV|dkrdttfSdddddfdd }dddddd fd d }d ||fSdttfS) zg Determine the correct setter functions based on whether a class is frozen and/or slotted. Trrkrrcs&t|rt|||Sd|d|SN _inst_dict['z'] = )rrrr~rr fmt_setters  z&_determine_setters..fmt_setterrrcs4|st|rt||||Sd|d|||Sr)rrrrrrrfmt_setter_with_convertersz5_determine_setters..fmt_setter_with_converter)z_inst_dict = self.__dict__)rrrr)rrr~rrrrr_determine_setterss rzlist[Attribute]ztuple[str, dict, dict]) rgrU is_slotted call_pre_initrcall_post_initdoes_cache_hashr~rrr method_namerc $ Cs|r dgng} | r| dt|||\} }}| | g}g}g}i}ddi}|D]}|jrj|||j}|jdk p|jtjk o| }|j}t |j t }|r|j j rdnd}|j rt |j tst|j }n|j }|jdkr|r\t|jf}|dk r0| |||d|d |||j |||j<n| |||d|d ||j j||<nT|dk r| ||d |d |||j |||j<n| ||d |d |n|j tk r<|s<|d |d }|jr||n |||dk r&| ||||||j |||j<n| ||||nb|r<|d }|jr`||n ||| d|dt|jf}|dk r| d|||||| d| d|||d|d |||j |||j<nB| d||||| d| d|||d|d ||j j||<nb|jrP||n |||dk r| ||||||j |||j<n| |||||jdkrT|jdk r|dkr|j||<qT|dk rT|jrT|j||<qT|rNt|d<| d|D]L}d|j}d|j}| d|d|d|jd |j||<|||<q|r^| d|r|r|r~dtd}n dtd}n dtd}| ||rd d!d"|D} | d#| d d$|}|}!|r<||rd$ndd%d$|7}d$d&d'd(d"|DD}"|!|!r.d$nd7}!|!|"7}!|rX|rXd)|!d | d*<d+}#d,| d|d-| rz|#| nd.d/||fS)0z Return a script of an initializer for *attrs*, a dict of globals, and annotations for the initializer. The globals are required by the generated script. zself.__attrs_pre_init__()z$_setattr = _cached_setattr_get(self)rNrrDFrrbz attr_dict['z '].defaultz =attr_dict['z=NOTHINGzif z is not NOTHING:r[zelse:Trz#if _config._run_validators is True:Z__attr_validator_Z__attr_z(self, z, self.zself.__attrs_post_init__()rz', None)rz '] = Nonernz = Nonerccss |]}|jrd|jVqdS)rnN)r,rVrrrrrsz(_attrs_to_init_script..zBaseException.__init__(self, rz*, cSsg|]}|d|qS)=r)rZ kw_arg_namerrrrsz)_attrs_to_init_script..css|]}|ddVqdS)rrN)split)rZkwarrrrszself.__attrs_pre_init__(rz zdef z): passr])r_rrr(rVr4rrBr5r;r'r: takes_selfr-rr,_INIT_FACTORY_PAT_get_global_namerArr/r%_first_param_typerrra)$rgrUrrrrrr~rrrrrZ extra_linesrrargsZ kw_only_argsZattrs_to_validateZnames_for_globalsrrrdrZarg_nameZ has_factoryZ maybe_selfr-Zinit_factory_nameargZval_nameZinit_hash_cachevalsZ pre_init_argsZpre_init_kw_only_argsNLrrrrs                                          "  r)rVrcCs |dS)z The default __init__ parameter name for a field. This performs private-name adjustment via leading-unscore stripping, and is the default value of Attribute.alias if not provided. rd)lstriprrrrrsrc @sTeZdZdZdZdddZddZedd d Zd d Z d dZ ddZ ddZ dS)ra *Read-only* representation of an attribute. .. warning:: You should never instantiate this class yourself. The class has *all* arguments of `attr.ib` (except for ``factory`` which is only syntactic sugar for ``default=Factory(...)`` plus the following: - ``name`` (`str`): The name of the attribute. - ``alias`` (`str`): The __init__ parameter name of the attribute, after any explicit overrides and default private-attribute-name handling. - ``inherited`` (`bool`): Whether or not that attribute has been inherited from a base class. - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The callables that are used for comparing and ordering objects by this attribute, respectively. These are set by passing a callable to `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also :ref:`comparison customization `. 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 :ref:`field transformer ` hook receives a list of them. - The ``alias`` property exposes the __init__ parameter name of the field, with any overrides and default private-attribute handling applied. .. 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. .. versionadded:: 21.1.0 *eq_key* and *order_key* .. versionadded:: 22.2.0 *alias* For the full version history of the fields, see `attr.ib`. )rVr'r(r)r0r1r2r3r+r,r.r%r-r/rur4r5NFcCst||p | |p|d\} }}}t|}|d||d||d||d||d| |d||d||d ||d ||d ||d | |d | rtt| nt|d| |d| |d||d||d|dS)NTrVr'r(r)r0r1r2r3r+r,r-r.r%r/rur4r5)r6rrtypesMappingProxyTyper_EMPTY_METADATA_SINGLETON)rrVr'r(r)r*r+r,rur.r%r-r/r0r1r2r3r4r5 bound_setattrrrrrs:                 zAttribute.__init__cCs tdSr"rrrrrr4 szAttribute.__setattr__c sZ|dkrj}njdk r&d}t|fddtjD}|f|jj|ddd|S)Nz8Type annotation and type argument cannot both be presentcs i|]}|dkr|t|qS))rVr(r'r%rur)rrrrrr? s z0Attribute.from_counting_attr..F)rVr(r'r%r*ru)r%r8rr _validator_default)rqrVrr%rB inst_dictrrrr7 s$   zAttribute.from_counting_attrcKst|}|||S)a Copy *self* and apply *changes*. This works similarly to `attrs.evolve` but that function does not work with {class}`Attribute`. It is mainly meant to be used for `transform-fields`. .. versionadded:: 20.3.0 )copy _setattrsr)rchangesnewrrrryV s zAttribute.evolvecstfddjDS)( Play nice with pickle. c3s*|]"}|dkrt|ntjVqdS)r.N)rxrr.rrrrrl sz)Attribute.__getstate__..r=rrrrrrh s zAttribute.__getstate__cCs|t|j|dSrN)rrrrrrrrrq szAttribute.__setstate__cCsLt|}|D]8\}}|dkr*|||q|||r@tt|ntqdS)Nr.)rrrrrr)rZname_values_pairsrrVrrrrrw s   zAttribute._setattrs) NNNFNNNNNN)N) rrrrrrrr rryrrrrrrrrs(* 7  rcCs2g|]*}t|tddddd|dkddt|d qS)NTFr.) rVr'r(r)r*r0r2r+r,rur5)rrrrrrrr srrxcCsg|]}|jdkr|qSrtrrrrrr s cCs g|]}|jr|jdkr|qSrt)r+rVrrrrr s c@sjeZdZdZdZedddDeddddddd dd ddd dd dd fZd Zd d Z ddZ ddZ dS)r@a Intermediate representation of attributes that uses a counter to preserve the order in which the attributes have been defined. *Internal* data structure of the attrs library. Running into is most likely the result of a bug like a forgotten `@attr.s` decorator. )rrr)r0r1r2r3r+r,r.rr-r%r/r4r5ccs8|]0}t|t|tdddddddddddddVqdS)NTFrVr5r'r(r)r*r+r,r/r0r1r2r3rur4)rrrrrrrr s$z_CountingAttr.) rrr)r0r2r+r,r4r5r.NTFrrcCsttjd7_tj|_||_||_||_||_| |_| |_| |_ ||_ ||_ ||_ ||_ | |_| |_||_||_dSr)r@ cls_counterrrrr-r)r0r1r2r3r+r,r.r%r/r4r5)rr'r(r)r*r+r,r-r.r%r/r0r1r2r3r4r5rrrr s"z_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)rr?rr7rrrr( 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)rrrr:rrrrr'" s z_CountingAttr.default) rrrrrr=rrsrrr(r'rrrrr@ s61%r@c@s.eZdZdZdZd ddZddZdd Zd S) r:a Stores a factory callable. If passed as the default value to `attrs.field`, the factory is used to generate a new value. Args: factory (typing.Callable): A callable that takes either none or exactly one mandatory positional argument depending on *takes_self*. takes_self (bool): Pass the partially initialized instance that is being initialized as a positional argument. .. versionadded:: 17.1.0 *takes_self* rArFcCs||_||_dSr"r)rrArrrrrM szFactory.__init__cstfddjDS)rc3s|]}t|VqdSr"rrrrrrU sz'Factory.__getstate__..rrrrrrQ szFactory.__getstate__cCs&t|j|D]\}}t|||q dSr)rrr)rrrVrrrrrW szFactory.__setstate__N)F)rrrrrrrrrrrrr:8 s  r:cCs(g|] }t|tddddddddd qSNTF) rVr'r(r)r*r0r2r+r,rurrrrrrr_ s c@sZeZdZdZdZdddddZedddd d Zdddd d d ZddZ ddZ dS)rae Stores a converter callable. Allows for the wrapped converter to take additional arguments. The arguments are passed in the order they are documented. Args: converter (Callable): A callable that converts the passed value. takes_self (bool): Pass the partially initialized instance that is being initialized as a positional argument. (default: `False`) takes_field (bool): Pass the field definition (an :class:`Attribute`) into the converter as a positional argument. (default: `False`) .. versionadded:: 24.1.0 )r-r takes_fieldrZ _global_name__call__Frrcs|_|_|_t|}|_js@js@fdd_nFjr\js\fdd_n*jsxjrxfdd_nfdd_|}|dk r|jjd<dS)Ncs |Sr"r-)rrd__rrrr rz$Converter.__init__..cs ||Sr"r)rinstancerrrrr scs ||Sr"r)rrr,rrrr scs|||Sr"r)rrr,rrrr sr) r-rrr get_first_param_typerrget_return_typer)rr-rrexrtrrrr s    zConverter.__init__rk)rdrcCs d|S)zh Return the name that a converter for an attribute name *attr_name* would have. Z__attr_converter_r)rdrrrr szConverter._get_global_name)rdrrcCs|js"|js"||d|dS|jrJ|jrJ||d|d|dS|jrf||d|dS||d|d|dS)z Return a string that calls the converter for an attribute name *attr_name* and the value in variable named *value_var* according to `self.takes_self` and `self.takes_field`. rrbz, self, attr_dict['z'])z, self)z , attr_dict[')rrr)rrdrrrrr s  zConverter._fmt_converter_callcCs|j|j|jdS)zx Return a dict containing only converter and takes_self -- the rest gets computed when loading. r-rrrrrrrr szConverter.__getstate__cCs|jf|dS)z+ Load instance from state. NrRrrrrr szConverter.__setstate__N) rrrrrrr rrrrrrrrrr s  cCs(g|] }t|tddddddddd qSrrrrrrr s rc sJt|tr|}n*t|ttfr.dd|D}n d}t||dd}|dd}|dd} i|dk rt||dk r|d<|dk r|d<| dk r| d<t||ifdd } t t t t d jd d | _W5QRX|d d} t| |d|dd\|d<|d<tfd|i|| } dd|D| _| S)a A quick way to create a new class called *name* with *attrs*. Args: name (str): The name for the new class. attrs( list | dict): A list of names or a dictionary of mappings of names to `attr.ib`\ s / `attrs.field`\ s. 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. bases (tuple[type, ...]): Classes that the new class will subclass. class_body (dict): An optional dictionary of class attributes for the new class. attributes_arguments: Passed unmodified to `attr.s`. Returns: type: A new class with *attrs*. .. versionadded:: 17.1.0 *bases* .. versionchanged:: 18.1.0 If *attrs* is ordered, the order is retained. .. versionchanged:: 23.2.0 *class_body* cSsi|] }|tqSr)rCrrrrr szmake_class..z(attrs argument must be a dict or a list.rNrrcs |Sr")r)rbodyrrr rzmake_class..rr__main__r*r0r2TrcSs"i|]\}}|jdk r||jqSr")r%rrrrr9 s )r;rr<r=r7poprr new_classrrrr8r _getframe f_globalsrrrKrrr) rVrgbasesZ class_bodyZattributes_argumentsZcls_dictrBrrZ user_inittype_r*rqrrr make_class sN       r)rr^c@seZdZdZeZddZdS) _AndValidatorz2 Compose many validators to a single one. cCs|jD]}||||qdSr") _validators)rrrrrrrrrK s z_AndValidator.__call__N)rrrrrCrrrrrrrC srcGs6g}|D] }|t|tr |jn|gqtt|S)a A validator that composes multiple validators into one. When called on a value, it runs all wrapped validators. Args: validators (~collections.abc.Iterable[typing.Callable]): Arbitrary number of validators. .. versionadded:: 17.1.0 )rr;rrr=)Z validatorsrr(rrrr?P s r?csfdd}s.td}|j||dnTtd}|rL||jd<d}tsht|trh|j }t| }|r||jd<t|d d d S) a A converter that composes multiple converters into one. When called on a value, it runs all wrapped converters, returning the *last* value. Type annotations will be inferred from the wrapped converters', if they have any. converters (~collections.abc.Iterable[typing.Callable]): Arbitrary number of converters. .. versionadded:: 20.1.0 cs,D]"}t|tr||||n||}q|Sr")r;r)r?rr,c convertersrrpipe_converterw s zpipe..pipe_converterA)r?rrr?rNrTr) typingTypeVarrrr rr r;rrr)rrrtlastrrrrr>g s     r>)NrD)N)T)NNNNNNNFFTFFFFFNNFFNNNTN)N)NN)b __future__rrrrrrrrrSrrroperatorrrDrrrrr r r r r exceptionsrrrrobjectrrrrnrrrrr>rrrEnumrrintr!rCrMrZrerfrorrrrrrrrrrKr6rOrgrrSrr%rrr4r3r<rrrrrrr*rrrrrrrrrZ_ar@r:Z_frrrr?rrrrs4       k  m: ,  ^ G(8 9 .O   /& J     ' d  X