o ]Lbb@sddlmZmZmZddlZddlZddlmZddlm Z ddl m Z m Z m Z mZmZddlmZmZmZejZdZd Zd ZeiZGd d d eZeZ edd d dd difddZddZddZddZ ddZ!  dBddZ"e r{ddZ#nddZ#ddZ$dCd d!Z%dCd"d#Z&dDd$d%Z'd&d'Z(d(d)Z)d*d+Z*d,d-Z+d.d/Z,Gd0d1d1eZ-d2d3e-j.DZ/e%e&e'e-e/d4e/d4d5d3e/Dd4Z-Gd6d7d7eZ0e&e'e0Z0e"d dd8Gd9d:d:eZ1effd;d<Z2e"d d d=Gd>d?d?eZ3d@dAZ4dS)E)absolute_importdivisionprint_functionN) itemgetter)_config)PY2 iteritemsisclassiterkeysmetadata_proxy)DefaultAlreadySetErrorFrozenInstanceErrorNotAnAttrsClassErrorz__attr_convert_{}z__attr_factory_{}z/ {attr_name} = property(itemgetter({index}))c@s@eZdZdZddZddZddZdd Zd d Zd d Z dS)_Nothingz Sentinel class to indicate the lack of a value when ``None`` is ambiguous. All instances of `_Nothing` are equal. cC|SNselfrrA/usr/lib/python3/dist-packages/mercurial/thirdparty/attr/_make.py__copy__z_Nothing.__copy__cCrrr)r_rrr __deepcopy__"rz_Nothing.__deepcopy__cCs |jtkSr) __class__rrotherrrr__eq__% z_Nothing.__eq__cCs ||k Srrrrrr__ne__(rz_Nothing.__ne__cCdS)NNOTHINGrrrrr__repr__+rz_Nothing.__repr__cCr!)Nl>[=rrrrr__hash__.rz_Nothing.__hash__N) __name__ __module__ __qualname____doc__rrrr r#r$rrrrrs rTc Cs8|dur|dur|durtdt||||||||dS)a Create a new attribute on a class. .. warning:: Does *not* do anything unless the class is also decorated with :func:`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 :class:`Factory`, its callable will be used to construct a new value (useful for mutable datatypes 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 :exc:`TypeError` will be raised. The default can also be set using decorator notation as shown below. :type default: Any value. :param validator: :func:`callable` that is called by ``attrs``-generated ``__init__`` methods after the instance has been initialized. They receive the initialized instance, the :class:`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 :func:`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 bool repr: Include this attribute in the generated ``__repr__`` method. :param bool cmp: Include this attribute in the generated comparison methods (``__eq__`` et al). :param hash: Include this attribute in the generated ``__hash__`` method. If ``None`` (default), mirror *cmp*'s value. This is the correct behavior according the Python spec. Setting this value to anything else than ``None`` is *discouraged*. :type hash: ``bool`` or ``None`` :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 convert: :func:`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 :ref:`extending_metadata`. .. versionchanged:: 17.1.0 *validator* can be a ``list`` now. .. versionchanged:: 17.1.0 *hash* is ``None`` and therefore mirrors *cmp* by default . NTF6Invalid value for hash. Must be True, False, or None.default validatorreprcmphashinitconvertmetadata) TypeError _CountingAttrr*rrrattr8sFr5cCsvd|}d|dg}|r"t|D]\}}|tj||dqn|ddti}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 passr exec)format enumerateappend_tuple_property_patrevalcompilejoin)cls_name attr_namesattr_class_nameattr_class_templateir7globsrrr_make_attr_tuple_classs   rHc sRgt|jddD]}t|dd}|dur#fdd|Dq |dur3dd|jD}n d dt|D}d dt|d d d D}dd|D}t|j |}|ddt|dd d D|_ d}|j D]7} |dur| vrt || j | |dur| j tur| jdurtdj| d|dur| j tur| jdurd}qodS)z Transforms all `_CountingAttr`s on a class into `Attribute`s and saves the list in `__attrs_attrs__`. If *these* is passed, use that and don't look for them on the class. r__attrs_attrs__Nc3s|] }|vr|VqdSrr.0a super_clsrr z#_transform_attrs..cSs"g|] \}}t|tr||fqSr isinstancer4rLnamer5rrr sz$_transform_attrs..cSsg|]\}}||fqSrr)rLrUcarrrrVs cSg|] \}}tj||dqS)rUrW Attributefrom_counting_attrrLr7rWrrrrV cS |djSNrcountererrr z"_transform_attrs..)keycSsg|]}|jqSrrUrKrrrrVscSrXrYrZr]rrrrVr^cSr_r`rarcrrrrerfFTzqNo mandatory attributes allowed after an attribute with a default value or factory. Attribute in question: {a!r})rM)reversed__mro__getattrextend__dict__itemsr sortedrHr%rJsetattrrUr+r"r0 ValueErrorr;) clsthesec sub_attrsca_listnon_super_attrsrC AttrsClass had_defaultrMrrNr_transform_attrssJ       rzcCt)z4 Attached to frozen classes as __setattr__. rrrUvaluerrr_frozen_setattrsrcCr{)z4 Attached to frozen classes as __delattr__. r|)rrUrrr_frozen_delattrsrrFc s0f dd} |dur| S| |S)a A class decorator that adds `dunder `_\ -methods according to the specified attributes using :func:`attr.ib` or the *these* argument. :param these: A dictionary of name to :func:`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. :type these: :class:`dict` of :class:`str` to :func:`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 repr: Create a ``__repr__`` method with a human readable represantation of ``attrs`` attributes.. :param bool str: Create a ``__str__`` method that is identical to ``__repr__``. This is usually not necessary except for :class:`Exception`\ s. :param bool cmp: Create ``__eq__``, ``__ne__``, ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` methods that compare the class as if it were a tuple of its ``attrs`` attributes. But the attributes are *only* compared, if the type of both classes is *identical*! :param hash: If ``None`` (default), the ``__hash__`` method is generated according how *cmp* and *frozen* are set. 1. If *both* are True, ``attrs`` will generate a ``__hash__`` for you. 2. If *cmp* is True and *frozen* is False, ``__hash__`` will be set to None, marking it unhashable (which it is). 3. If *cmp* is False, ``__hash__`` will be left untouched meaning the ``__hash__`` method of the superclass will be used (if superclass 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 the `Python documentation \ `_ and the `GitHub issue that led to the default behavior \ `_ for more details. :type hash: ``bool`` or ``None`` :param bool init: Create a ``__init__`` method that initialiazes 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 slots_-style class that's more memory-efficient. See :ref:`slots` for further ramifications. :param bool frozen: Make instances immutable after initialization. If someone attempts to modify a frozen instance, :exc:`attr.exceptions.FrozenInstanceError` is raised. Please note: 1. This is achieved by installing a custom ``__setattr__`` method on your class so you can't implement an own one. 2. True immutability is impossible in Python. 3. This *does* have a minor a runtime performance :ref:`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)``. .. _slots: https://docs.python.org/3.5/reference/datamodel.html#slots .. versionadded:: 16.0.0 *slots* .. versionadded:: 16.1.0 *frozen* .. versionadded:: 16.3.0 *str*, and support for ``__attrs_post_init__``. .. versionchanged:: 17.1.0 *hash* supports ``None`` as value which is also the default now. cst|dddur tddurdurtdr/dur)dd|jD}ntt}t|t|p9}durDt |d}durL|j |_ durTt |}durddurddurdtd duspdurqdurqndusdurdurdurt |}nd|_durt||}|durt|_t|_durt|}durt|j}t||d <|D]}||dq|d dt|d d}t||j|j|}|dur||_|S) Nrz(attrs only works with new-style classes.FTz3__str__ can only be generated if a __repr__ exists.cSsg|] \}}t|tr|qSrrRrTrrrrVNs z,attributes..wrap..)nsr) __slots__rmr')rkr3rqrmrnlistr rz_has_frozen_superclass _add_reprr#__str___add_cmp _add_hashr$ _add_initr __setattr__r __delattr__ _add_pickledicttuplepoptyper% __bases__r')rrrveffectively_frozencls_dictca_namequalname r.frozenr/r0r-repr_nsslotsstrrsrrwrapBs^           zattributes..wrapNr) maybe_clsrsrr-r.r/r0rrrrrrr attributessUBrcCs"t|jddtjko|jjtjkS)b Check whether *cls* has a frozen ancestor by looking at its __setattr__. r&N)rkrrr&r%rrrrrrs rcCs |jtkS)r)rrrrrrrs cstfdd|DS)z: Create a tuple of all values of *obj*'s *attrs*. c3|] }t|jVqdSrrkrUrKobjrrrPrQz"_attrs_to_tuple..)r)rattrsrrr_attrs_to_tuplesrcs.dur dd|jDfdd}||_|S)z% Add a hash method to *cls*. NcSs.g|]}|jdus|jdur|jdur|qS)TN)r/r.rKrrrrVs z_add_hash..cstt|S1 Automatically created by attrs. )r/rrrrrhash_sz_add_hash..hash_)rJr$)rrrrrrrrs rcsdur dd|jDfddfddfdd }fd d }fd d }fdd}fdd}|_||_||_||_||_||_|S)z* Add comparison methods to *cls*. NcSg|]}|jr|qSr)r.rKrrrrVz_add_cmp..cs t|S)z& Save us some typing. )rrrrrattrs_to_tuples z _add_cmp..attrs_to_tuplecs |j|jur||kStSr)rNotImplementedrrrreq z_add_cmp..eqcs||}|tur tS| Sr)r)rrresult)rrrnes z_add_cmp..necs t||jr||kStSrrSrrrrrrltrz_add_cmp..ltcs t||jr||kStSrrrrrrlerz_add_cmp..lecs t||jr||kStSrrrrrrgtrz_add_cmp..gtcs t||jr||kStSrrrrrrgerz_add_cmp..ge)rJrr __lt____le____gt____ge__)rrrrrrrrr)rrrrrs     rcs0dur dd|jDfdd}||_|S)z% Add a repr method to *cls*. NcSrr)r-rKrrrrV rz_add_repr..csjj}durt|dd}|dur|ddd}n |j}nd|j}d|dfd d DS) rNr'z>.rrI.z{0}({1}), c3s*|]}|jdtt|jVqdS)=N)rUr-rkrKrrrrPs"z+_add_repr..repr_..)rrkrsplitr%r;rA)rreal_clsr class_namerrrrrepr_s z_add_repr..repr_)rJr#)rrrrrrrrrs rc Csdd|jD}t}t|}t|ts|d}||d| }t ||t |dd\}}i}t ||d} t dd |D} |t| d |d urSt|d <t| |||d } t|d|d |ftj|<| |_|S)zR Add a __init__ method to *cls*. If *frozen* is True, make it immutable. cSs g|] }|js |jtur|qSr)r0r+r"rKrrrrV)s  z_add_init..zutf-8z__attrs_post_init__Fr:css|]}|j|fVqdSrrhrKrrrrP=z_add_init..)r" attr_dictT_cached_setattr__init__N)rJhashlibsha1r-rSbytesencodeupdater; hexdigest_attrs_to_scriptrkr@rr" _obj_setattrr?len splitlines linecachecacher) rrrrrrunique_filenamescriptrGlocsbytecoderr0rrrr%s@       rcCs dd}dd}||_||_|S)zC Add pickle helpers, needed for frozen and slotted classes cstfddtjDS)( Play nice with pickle. c3rrrrKrrrrP]rQz9_add_pickle.._slots_getstate__..)rfieldsrrrrr_slots_getstate__Ysz&_add_pickle.._slots_getstate__cSs6t|t}tt|j|D] \}}||j|qdS)rN)r__get__r[ziprrrU)rstate__bound_setattrrMr~rrr_slots_setstate___s z&_add_pickle.._slots_setstate__) __getstate__ __setstate__)rrrrrrrrUs rcCs8t|stdt|dd}|durtdj|d|S)a Returns 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 accesors) of :class:`attr.Attribute` .. versionchanged:: 16.2.0 Returned tuple allows accessing the fields by name. zPassed object must be a class.rJNz({cls!r} is not an attrs-decorated class.r)r r3rkrr;)rrrrrrrls  rcCsDtjdurdSt|jD]}|j}|dur|||t||jq dS)z Validate all attributes on *inst* that have a validator. Leaves all exceptions through. :param inst: Instance of a class with ``attrs`` attributes. FN)r_run_validatorsrrr,rkrU)instrMvrrrvalidates rc Csg}|dur|ddd}dd}ndd}dd}g}g}i}|D]Q} | jr/|| | j} | jd } t| jt} | rG| jjrGd } nd } | jd ur| rt | j}| j d urt||| |d | t | j}| j ||<n ||| |d | | jj ||<q$| j d ur||| dj | dt | j}| j ||<q$||| dj | dq$| jtur| s|dj | | d| j d ur||| | | j |t | j<q$||| | q$| rQ|dj | d|dj | dt | j}| j d ur,|d|| | |d|d|| |d | | j |t | j<n|d|| | |d|d|| |d | | jj ||<q$|| | j d urn||| | | j |t | j<q$||| | q$|rt|d<|d|D]#} d | j}d | j} |d || | j| j||<| || <q|r|ddj d||rd |nd!d"|fS)#z Return a script of an initializer for *attrs* and a dict of globals. The globals are expected by the generated script. If *frozen* is True, we cannot set the attributes directly so we use a cached ``object.__setattr__``. Tz8_setattr = _cached_setattr.__get__(self, self.__class__)cSd||dS)Nz(_setattr('%(attr_name)s', %(value_var)s)r7 value_varrrrrr fmt_setterz$_attrs_to_script..fmt_settercSt|}d|||dS)Nz2_setattr('%(attr_name)s', %(conv)s(%(value_var)s))r7rconv_init_convert_patr;r7r conv_namerrrfmt_setter_with_converter z3_attrs_to_script..fmt_setter_with_convertercSr)Nzself.%(attr_name)s = %(value)sr7r~rrrrrrrcSr)Nz,self.%(attr_name)s = %(conv)s(%(value_var)s)rrrrrrrrrrr9FNz({0})z attr_dict['{attr_name}'].default)r7z+{arg_name}=attr_dict['{attr_name}'].default)arg_namer7z{arg_name}=NOTHING)rzif {arg_name} is not NOTHING:z zelse:rz#if _config._run_validators is True:z__attr_validator_{}z __attr_{}z {}(self, {}, self.{})zself.__attrs_post_init__()z(def __init__(self, {args}): {lines} rz pass)argslines)r=r,rUlstriprSr+Factory takes_selfr0_init_factory_patr;r1rfactoryr"rrA)rr post_initrrrrattrs_to_validatenames_for_globalsrMr7r has_factory maybe_selfinit_factory_namerval_namerrrrs                                 rc@sDeZdZdZdZ dddZddZedd Zd d Z d d Z dS)r[z *Read-only* representation of an attribute. :attribute name: The name of the attribute. Plus *all* arguments of :func:`attr.ib`. ) rUr+r,r-r.r/r0r1r2Nc Cs|t|t} | d|| d|| d|| d|| d|| d|| d|| d|| d | r9t| dStdS) NrUr+r,r-r.r/r0r1r2)rrr[r _empty_metadata_singleton) rrUr+r,r-r.r/r0r1r2 bound_setattrrrrrBs         zAttribute.__init__cCr{rr|r}rrrrRszAttribute.__setattr__cs.fddtjD}|d|jjd|S)Ncs i|] }|dvr|t|qS)rUr,r+)rk)rLkrWrr Ws  z0Attribute.from_counting_attr..r r)r[r _validator_default)rrrUrW inst_dictrr rr\Us zAttribute.from_counting_attrcstfddjDS)rc3s,|]}|dkr t|ntjVqdS)r2N)rkrr2rLrUrrrrPgs  z)Attribute.__getstate__..)rrrrrrrcs zAttribute.__getstate__cCsPt|t}t|j|D]\}}|dkr|||q |||r"t|ntq dS)rr2N)rrr[rrr r)rrr rUr~rrrrks  zAttribute.__setstate__NN) r%r&r'r(rrr classmethodr\rrrrrrr[5s   r[c Cs&g|]}t|tddd|dkddqS)NTr2rUr+r,r-r.r/r0r[r"rrrrrVxs   rVrcCrr)r/rKrrrrV~rc @sZeZdZdZdZedddDedddddd dd fZd Zd d Z ddZ ddZ dS)r4a 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. ) rbrr-r.r/r0r2rr1c cs&|]}t|tddddddVqdS)NTrrrrrrrPs z_CountingAttr.)rbrr-r.r/r0r2NTFrrc Cshtjd7_tj|_||_|rt|ttfrt||_n||_||_ ||_ ||_ ||_ ||_ ||_dSr`)r4 cls_counterrbrrSrrand_rr-r.r/r0r1r2) rr+r,r-r.r/r0r1r2rrrrs  z_CountingAttr.__init__cCs&|jdur ||_|St|j||_|S)z Decorator that adds *meth* to the list of validators. Returns *meth* unchanged. .. versionadded:: 17.1.0 N)rrrmethrrrr,s z_CountingAttr.validatorcCs"|jturtt|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"r rrrrrr+s z_CountingAttr.default) r%r&r'r(rrr[rJrrr,r+rrrrr4s  r4)rr0c@s&eZdZdZeZeZdddZdS)ra Stores a factory callable. If passed as the default value to :func:`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)rr)rrrrrrrs zFactory.__init__N)F)r%r&r'r(r5rrrrrrrrs  rcKsTt|tr|}nt|ttfrtdd|D}ntdtdi|t|||S)a A quick way to create a new class called *name* with *attrs*. :param name: The name for the new class. :type name: str :param attrs: A list of names or a dictionary of mappings of names to attributes. :type attrs: :class:`list` or :class:`dict` :param tuple bases: Classes that the new class will subclass. :param attributes_arguments: Passed unmodified to :func:`attr.s`. :return: A new class with *attrs*. :rtype: type .. versionadded:: 17.1.0 *bases* css|]}|tfVqdSr)r5rKrrrrPrzmake_class..z(attrs argument must be a dict or a list.Nr)rSrrrr3rr)rUrbasesattributes_argumentsrrrr make_classs r)rr/c@seZdZdZeZddZdS) _AndValidatorz2 Compose many validators to a single one. cCs|jD]}||||qdSr) _validators)rrr5r~rrrr__call__s z_AndValidator.__call__N)r%r&r'r(r5rrrrrrrs rcGs6g}|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 validators: Arbitrary number of validators. :type validators: callables .. versionadded:: 17.1.0 )rlrSrrr) validatorsvalsr,rrrrs  r) NNNTTNTFFFrr)5 __future__rrrrroperatorrr9r_compatrr r r r exceptionsr rrobjectrrrrr>rrr"r5rHrzrrrrrrrrrrrrrr[r_ar4rrrrrrrrsr   V5      N0C  F  "