a
    lcS                    @   s  d Z ddlZddlZddlZddlZddlZddlZddlZddlZ	ddl
mZ ddlmZmZ ddlmZ ddlmZmZmZmZ ddlmZ dd	lmZ dd
lmZ eeeefZ e!fZ"g dZ#edddZ$edddZ%e$Z&G dd de'Z(e)dZ*dd Z+e Z,dd Z-dd Z.dd Z/dd Z0dd Z1G d d! d!Z2dd"d#Z3d$d% Z4G d&d' d'Z5G d(d) d)Z6e6Z7G d*d+ d+Z8G d,d- d-e8Z9G d.d/ d/Z:d0d1 Z;G d2d3 d3e!Z<G d4d5 d5e<Z=d6d7d8d9Z>d:d; Z?d<d= Z@d>d? ZAG d@dA dAe8ZBG dBdC dCeBZCG dDdE dEeBZDG dFdG dGeBZEG dHdI dIe<dJZFG dKdL dLeFe=dJZGG dMdN dNe9ZHG dOdP dPeHZIG dQdR dReHZJG dSdT dTZKG dUdV dVeKeIZLG dWdX dXeKeJZMG dYdZ dZeHZNG d[d\ d\e9ZOG d]d^ d^e9ZPd_d` ZQG dadb dbe9ZRG dcdd ddeRZSeReS ZTZUeRZVG dedf dfe9ZWG dgdh dheWZXG didj dje9ZYG dkdl dleYZZG dmdn dne9Z[G dodp dpe[Z\G dqdr dre9Z]G dsdt dte]Z^G dudv dve9Z_G dwdx dxe_Z`G dydz dze9ZaG d{d| d|eaZbG d}d~ d~e9ZcG dd decZdG dd decZeG dd deJZfG dd defZgG dd degZhG dd defZiG dd deJZjG dd de9ZkG dd de9ZlG dd de9ZmG dd de9ZndS )a  
A lightweight Traits like module.

This is designed to provide a lightweight, simple, pure Python version of
many of the capabilities of enthought.traits.  This includes:

* Validation
* Type specification with defaults
* Static and dynamic notification
* Basic predefined types
* An API that is similar to enthought.traits

We don't support:

* Delegation
* Automatic GUI generation
* A full set of trait types.  Most importantly, we don't provide container
  traits (list, dict, tuple) that can trigger notifications if their
  contents change.
* API compatibility with enthought.traits

There are also some important difference in our design:

* enthought.traits does not validate default values.  We do.

We choose to create this module because we need these capabilities, but
we need them to be pure Python so they work in all Python implementations,
including Jython and IronPython.

Inheritance diagram:

.. inheritance-diagram:: traitlets.traitlets
   :parts: 3
    N)literal_eval)warnwarn_explicit   )Bunch)add_articleclass_ofdescribe	repr_type)
getargspecimport_item)Sentinel);AllAnyBaseDescriptorBoolBytesCBoolCBytesCComplexCFloatCIntCLongCRegExpCUnicodeCallableCaselessStrEnumClassBasedTraitTypeComplex	ContainerDefaultHandlerDictDottedObjectNameEnumEventHandlerFloatForwardDeclaredInstanceForwardDeclaredMixinForwardDeclaredType	FuzzyEnumHasDescriptors	HasTraitsInstanceIntIntegerListLongMetaHasDescriptorsMetaHasTraits
ObjectNameObserveHandlerSet
TCPAddressThis
TraitError	TraitTypeTupleTypeUnicode	UndefinedUnionUseEnumValidateHandlerdefaultdirectional_linkdlinklinkobserveobserve_compatparse_notifier_namevalidater>   Z	traitletszA
Used in Traitlets to specify that no defaults are set in kwargs
r   zi
Used in Traitlets to listen to all types of notification or to notifications
from all trait attributes.
c                   @   s   e Zd ZdS )r9   N)__name__
__module____qualname__ rM   rM   O/var/www/html/django/DPS/env/lib/python3.9/site-packages/traitlets/traitlets.pyr9      s   r9   z[a-zA-Z_][a-zA-Z0-9_]*$c                 C   s   |   S NisidentifiersrM   rM   rN   rQ      s    rQ   c                 C   s:   t jd}|r|dkrdS | tvr2t|  dS dS dS )zZAdd our own checks for too many deprecation warnings.

    Limit to once per package.
    ZTRAITLETS_ALL_DEPRECATIONS0TFN)osenvironget_deprecations_shownadd)keyZenv_flagrM   rM   rN   _should_warn   s    
r[   c              
   C   s   dj |j||d}t|D ]}||jv r|} q4q|jddd }||f}t|sZdS z$t| phd}t	| d pzd}	W n: t
tfy }
 zt|d|
  t W Y d}
~
nd}
~
0 0 t|t||	 dS )	zShow deprecation warning about a magic method definition.

    Uses warn_explicit to bind warning to method definition instead of triggering code,
    which isn't relevant.
    z?{classname}.{method_name} is deprecated in traitlets 4.1: {msg})	classnamemethod_namemsg.r   r   Nz	<unknown>z
(inspection failed) %s)formatrJ   inspectgetmro__dict__rK   splitr[   getsourcefilegetsourcelinesOSError	TypeErrorr   DeprecationWarningr   )methodclsr]   r^   Zwarn_msgparentpackage_namerZ   fnamelinenoerM   rM   rN   _deprecated_method   s"    
(rq   c              
   C   s,   z
t | W S  tttfy&   |  Y S 0 dS )zwSafely evaluate an expression

    Returns original string if eval fails.

    Use only where types are ambiguous.
    N)r   	NameErrorSyntaxError
ValueErrorrR   rM   rM   rN   _safe_literal_eval   s    
ru   c                 C   s   t | tpt | tot| tS )zHReturns whether the given value is an instance or subclass of TraitType.)
isinstancer:   type
issubclass)trM   rM   rN   is_trait   s    rz   c                 C   sR   | t u st| tr| gS | r$t | v r*t gS | D ]}t|ts.td| q.| S dS )a  Convert the name argument to a list of names.

    Examples
    --------
    >>> parse_notifier_name([])
    [traitlets.All]
    >>> parse_notifier_name("a")
    ['a']
    >>> parse_notifier_name(["a", "b"])
    ['a', 'b']
    >>> parse_notifier_name(All)
    [traitlets.All]
    znames must be strings, not %rN)r   rv   strrh   )namesnrM   rM   rN   rH      s    
rH   c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
_SimpleTestc                 C   s
   || _ d S rO   valueselfr   rM   rM   rN   __init__  s    z_SimpleTest.__init__c                 C   s
   || j kS rO   r   )r   testrM   rM   rN   __call__
  s    z_SimpleTest.__call__c                 C   s
   d| j  S )Nz<SimpleTest(%r)r   r   rM   rM   rN   __repr__  s    z_SimpleTest.__repr__c                 C   s   |   S rO   )r   r   rM   rM   rN   __str__  s    z_SimpleTest.__str__N)rJ   rK   rL   r   r   r   r   rM   rM   rM   rN   r~     s   r~   c              	   C   sZ   g }t | D ]@}zt| |}W n ty0   Y q0 |r>||r|||f q|  |S )a  A safe version of inspect.getmembers that handles missing attributes.

    This is useful when there are descriptor based attributes that for
    some reason raise AttributeError even though they exist.  This happens
    in zope.inteface with the __provides__ attribute.
    )dirgetattrAttributeErrorappendsort)object	predicateresultsrZ   r   rM   rM   rN   
getmembers  s    r   c                  G   sf   | D ]\}t |dks tdt |\}}t|tsBtdt| || vrt|d|qdS )z.Validate arguments for traitlet link functions   zKEach linked traitlet must be specified as (HasTraits, 'trait_name'), not %rz%Each object must be HasTraits, not %rz has no trait N)lenrh   ry   rv   r,   rw   traits)Ztuplestupobj
trait_namerM   rM   rN   _validate_link(  s    
r   c                   @   sL   e Zd ZdZdZdddZdd Zejdd	 Z	d
d Z
dd Zdd ZdS )rE   aR  Link traits from different objects together so they remain in sync.

    Parameters
    ----------
    source : (object / attribute name) pair
    target : (object / attribute name) pair
    transform: iterable with two callables (optional)
        Data transformation between source and target and target and source.

    Examples
    --------
    >>> class X(HasTraits):
    ...     value = Int()

    >>> src = X(value=1)
    >>> tgt = X(value=42)
    >>> c = link((src, "value"), (tgt, "value"))

    Setting source updates target objects:
    >>> src.value = 5
    >>> tgt.value
    5
    FNc                 C   sB   t || || | _| _|r |ndd fd \| _| _|   d S )Nc                 S   s   | S rO   rM   xrM   rM   rN   <lambda>T      zlink.__init__.<locals>.<lambda>r   )r   sourcetarget
_transform_transform_invrE   r   r   r   Z	transformrM   rM   rN   r   Q  s    
zlink.__init__c              
   C   s   zlt | jd | jd | t| jd | jd  W | jd j| j| jd d | jd j| j| jd d n:| jd j| j| jd d | jd j| j| jd d 0 d S Nr   r   r|   )setattrr   r   r   r   rF   _update_target_update_sourcer   rM   rM   rN   rE   X  s    z	link.linkc                 c   s$   d| _ zd V  W d| _ nd| _ 0 d S NTFupdatingr   rM   rM   rN   _busy_updatingd  s    zlink._busy_updatingc                 C   s   | j r
d S |  Z t| jd | jd | |j t| jd | jd |jkr^td	| W d    n1 sr0    Y  d S )Nr   r   zCBroken link {}: the source value changed while updating the target.)
r   r   r   r   r   newr   r   r9   r`   r   changerM   rM   rN   r   l  s    
 zlink._update_targetc                 C   s   | j r
d S |  Z t| jd | jd | |j t| jd | jd |jkr^td	| W d    n1 sr0    Y  d S )Nr   r   zCBroken link {}: the target value changed while updating the source.)
r   r   r   r   r   r   r   r   r9   r`   r   rM   rM   rN   r   w  s    
 zlink._update_sourcec                 C   s<   | j d j| j| j d d | jd j| j| jd d d S r   )r   	unobserver   r   r   r   rM   rM   rN   unlink  s    zlink.unlink)N)rJ   rK   rL   __doc__r   r   rE   
contextlibcontextmanagerr   r   r   r   rM   rM   rM   rN   rE   6  s   

rE   c                   @   sD   e Zd ZdZdZdddZdd Zejdd	 Z	d
d Z
dd ZdS )rC   a  Link the trait of a source object with traits of target objects.

    Parameters
    ----------
    source : (object, attribute name) pair
    target : (object, attribute name) pair
    transform: callable (optional)
        Data transformation between source and target.

    Examples
    --------
    >>> class X(HasTraits):
    ...     value = Int()

    >>> src = X(value=1)
    >>> tgt = X(value=42)
    >>> c = directional_link((src, "value"), (tgt, "value"))

    Setting source updates target objects:
    >>> src.value = 5
    >>> tgt.value
    5

    Setting target does not update source object:
    >>> tgt.value = 6
    >>> src.value
    5

    FNc                 C   s6   |r|ndd | _ t|| || | _| _|   d S )Nc                 S   s   | S rO   rM   r   rM   rM   rN   r     r   z+directional_link.__init__.<locals>.<lambda>)r   r   r   r   rE   r   rM   rM   rN   r     s    
zdirectional_link.__init__c              
   C   st   zPt | jd | jd | t| jd | jd  W | jd j| j| jd d n| jd j| j| jd d 0 d S r   )r   r   r   r   r   rF   _updater   rM   rM   rN   rE     s    zdirectional_link.linkc                 c   s$   d| _ zd V  W d| _ nd| _ 0 d S r   r   r   rM   rM   rN   r     s    zdirectional_link._busy_updatingc                 C   sV   | j r
d S |  0 t| jd | jd | |j W d    n1 sH0    Y  d S Nr   r   )r   r   r   r   r   r   r   rM   rM   rN   r     s    
zdirectional_link._updatec                 C   s    | j d j| j| j d d d S r   )r   r   r   r   rM   rM   rN   r     s    zdirectional_link.unlink)N)rJ   rK   rL   r   r   r   rE   r   r   r   r   r   rM   rM   rM   rN   rC     s   


rC   c                   @   sV   e Zd ZU dZdZeje ed< dZ	ejej
ej  ed< dd Zdd Zd	d
 ZdS )r   a  Base descriptor class

    Notes
    -----
    This implements Python's descriptor protocol.

    This class is the base class for all such descriptors.  The
    only magic we use is a custom metaclass for the main :class:`HasTraits`
    class that does the following:

    1. Sets the :attr:`name` attribute of every :class:`BaseDescriptor`
       instance in the class dict to the name of the attribute.
    2. Sets the :attr:`this_class` attribute of every :class:`BaseDescriptor`
       instance in the class dict to the *class* that declared the trait.
       This is used by the :class:`This` trait to allow subclasses to
       accept superclasses for :class:`This` values.
    Nname
this_classc                 C   s   || _ || _dS )aE  Part of the initialization which may depend on the underlying
        HasDescriptors class.

        It is typically overloaded for specific types.

        This method is called by :meth:`MetaHasDescriptors.__init__`
        passing the class (`cls`) and `name` under which the descriptor
        has been assigned.
        N)r   r   r   rk   r   rM   rM   rN   
class_init  s    
zBaseDescriptor.class_initc                 C   s   d S rO   rM   )r   rk   rM   rM   rN   subclass_init  s    zBaseDescriptor.subclass_initc                 C   s   dS )aL  Part of the initialization which may depend on the underlying
        HasDescriptors instance.

        It is typically overloaded for specific types.

        This method is called by :meth:`HasTraits.__new__` and in the
        :meth:`BaseDescriptor.instance_init` method of descriptors holding
        other descriptors.
        NrM   r   r   rM   rM   rN   instance_init  s    
zBaseDescriptor.instance_init)rJ   rK   rL   r   r   ry   Optionalr{   __annotations__r   r<   r   r   r   r   rM   rM   rM   rN   r     s   
r   c                   @   s   e Zd ZU dZi Zejeejf e	d< dZ
dZdZeZejej e	d< eddddfddZd	d
 Zd+ddZdd Zdd Zd,ddZd-ddZdd Zdd Zdd Zdd Zdd Zdd  Zd.d!d"Zd/d#d$Zd%d& Zd'd( Z d)d* Z!dS )0r:   z!A base class for all trait types.metadataF	any valuedefault_valueNc                 K   s>  |t ur|| _|r|| _|dur&|| _|dur2|nd| _t|dkrd}t }|dus^J |jj	dkr|d7 }|j
}|dus^J q^|jdpd}	|	ddd }
td|
gt| }t|rtd	|f t|d
 t| jdkr| j | _| j| n|| _n| j | _|dur&|| jd< |dur:|| jd< dS )a  Declare a traitlet.

        If *allow_none* is True, None is a valid value in addition to any
        values that are normally valid. The default is up to the subclass.
        For most trait types, the default value for ``allow_none`` is False.

        If *read_only* is True, attempts to directly modify a trait attribute raises a TraitError.

        Extra metadata can be associated with the traitlet using the .tag() convenience method
        or by using the traitlet instance's .metadata dictionary.
        N r   r   r   rJ   r_   zmetadata-tagzmetadata %s was set from the constructor. With traitlets 4.1, metadata should be set using the .tag() method, e.g., Int().tag(key1='value1', key2='value2')
stacklevelconfighelp)r>   r   
allow_none	read_onlyr   r   ra   currentframef_codeco_namef_back	f_globalsrW   rd   tuplesortedr[   r   ri   r   copyupdate)r   r   r   r   r   r   kwargsr   fmodpkgrZ   rM   rM   rN   r     sF    


zTraitType.__init__c                 C   s   | j r|dkrdS |S )a
  Get a value from a config string

        such as an environment variable or CLI arguments.

        Traits can override this method to define their own
        parsing of config strings.

        .. seealso:: item_from_string

        .. versionadded:: 5.0
        NoneNr   r   rS   rM   rM   rN   from_stringM  s    zTraitType.from_stringc                 C   s,   | j tur| j S t| dr"|  S | j S dS )zThe default generator for this trait

        Notes
        -----
        This method is registered to HasTraits classes during ``class_init``
        in the same way that dynamic defaults defined by ``@default`` are.
        make_dynamic_defaultN)r   r>   hasattrr   r   rM   rM   rN   rB   ]  s
    

zTraitType.defaultc                 C   s   t dtdd | jS )zmDEPRECATED: Retrieve the static default value for this trait.
        Use self.default_value instead
        zRget_default_value is deprecated in traitlets 4.0: use the .default_value attributer   r   )r   ri   r   r   rM   rM   rN   get_default_valuem  s    zTraitType.get_default_valuec                 C   s,   t dtdd | || j}||j| j< |S )z<DEPRECATED: Set the static default value for the trait type.zSinit_default_value is deprecated in traitlets 4.0, and may be removed in the futurer   r   )r   ri   	_validater   _trait_valuesr   r   r   r   rM   rM   rN   init_default_valuex  s    zTraitType.init_default_valuec                 C   s   z|j | j }W n ty   || j}|tu r@tdtdd |j | ||}W d    n1 sh0    Y  ||j | j< |	t
| j||dd | Y S  ty   tdY n0 |S d S )NzxExplicit using of Undefined as the default value is deprecated in traitlets 5.0, and may cause exceptions in the future.r   r   rB   )r   r   ownerrw   z=Unexpected error in TraitType: default value not set properly)r   r   KeyErrortrait_defaultsr>   r   ri   cross_validation_lockr   _notify_observersr   	Exceptionr9   )r   r   rk   r   rB   rM   rM   rN   rW     s2    *zTraitType.getc                 C   s   |du r| S |  ||S dS )aM  Get the value of the trait by self.name for the instance.

        Default values are instantiated when :meth:`HasTraits.__new__`
        is called.  Thus by the time this method gets called either the
        default value or a user defined value (they called :meth:`__set__`)
        is in the :class:`HasTraits` instance.
        N)rW   )r   r   rk   rM   rM   rN   __get__  s    zTraitType.__get__c                 C   s   |  ||}z|j| j }W n ty4   | j}Y n0 ||j| j< zt||k}W n tyh   d}Y n0 |dur|| j|| d S )NFT)r   r   r   r   r   boolr   _notify_trait)r   r   r   	new_value	old_valueZsilentrM   rM   rN   set  s    
zTraitType.setc                 C   s&   | j rtd| j n| || dS )zSet the value of the trait by self.name for the instance.

        Values pass through a validation stage where errors are raised when
        impropper types, or types that cannot be coerced, are encountered.
        zThe "%s" trait is read-only.N)r   r9   r   r   r   rM   rM   rN   __set__  s    zTraitType.__set__c                 C   sB   |d u r| j r|S t| dr(| ||}|jdu r>| ||}|S )NrI   F)r   r   rI   _cross_validation_lock_cross_validater   rM   rM   rN   r     s    

zTraitType._validatec                 C   sr   | j |jv r0t| ||d}|j| j  ||}n>t|d| j  rnd| j  }t||}t||j|d ||| }|S )N)traitr   r   _%s_validate use @validate decorator instead.)r   _trait_validatorsr   r   r   rq   	__class__)r   r   r   Zproposal	meth_nameZcross_validaterM   rM   rN   r     s    


zTraitType._cross_validatec                 C   s*   t |trt| g|j S t| |gS d S rO   rv   r?   trait_typesr   otherrM   rM   rN   __or__  s    
zTraitType.__or__c                 C   s   | j S rO   )	info_textr   rM   rM   rN   info  s    zTraitType.infoc              	   C   s  |dur| j | f7  _ | jdurddd |j dd D }|durzd| jtd|||j d td	|j d
 f f|_ n(d| j||j d td	|j d
 f f|_ |nl| jdu rt||p|  | nL|durd| jt||  td	|}nd| j|  td	|}t|dS )a  Raise a TraitError

        Parameters
        ----------
        obj : HasTraits or None
            The instance which owns the trait. If not
            object is given, then an object agnostic
            error will be raised.
        value : any
            The value that caused the error.
        error : Exception (default: None)
            An error that was raised by a child trait.
            The arguments of this exception should be
            of the form ``(value, info, *traits)``.
            Where the ``value`` and ``info`` are the
            problem value, and string describing the
            expected value. The ``traits`` are a series
            of :class:`TraitType` instances that are
            "children" of this one (the first being
            the deepest).
        info : str (default: None)
            A description of the expected value. By
            default this is infered from this trait's
            ``info`` method.
        N of c                 s   s   | ]}t d |V  qdS )aN)r	   ).0ry   rM   rM   rN   	<genexpr>  r   z"TraitType.error.<locals>.<genexpr>r   zDThe '%s' trait of %s instance contains %s which expected %s, not %s.Zanr   Zther   z5The '%s' trait contains %s which expected %s, not %s.z2The '{}' trait of {} instance expected {}, not {}.z#The '{}' trait expected {}, not {}.)argsr   joinr	   r9   r   r`   r   )r   r   r   errorr   chainrp   rM   rM   rN   r    sL    


zTraitType.errorc                 C   s2   |dkrd}nd}t d| tdd | j||S )znDEPRECATED: Get a metadata value.

        Use .metadata[key] or .metadata.get(key, default) instead.
        r   z3use the instance .help string directly, like x.helpzduse the instance .metadata dictionary directly, like x.metadata[key] or x.metadata.get(key, default)Deprecated in traitlets 4.1, r   r   )r   ri   r   rW   )r   rZ   rB   r^   rM   rM   rN   get_metadata=  s
    zTraitType.get_metadatac                 C   s2   |dkrd}nd}t d| tdd || j|< dS )z[DEPRECATED: Set a metadata key/value.

        Use .metadata[key] = value instead.
        r   z;use the instance .help string directly, like x.help = valuezLuse the instance .metadata dictionary directly, like x.metadata[key] = valuer  r   r   N)r   ri   r   )r   rZ   r   r^   rM   rM   rN   set_metadataI  s
    zTraitType.set_metadatac                 K   s<   t | h d}|r,td| tdd | j| | S )a  Sets metadata and returns self.

        This allows convenient metadata tagging when initializing the trait, such as:

        Examples
        --------
        >>> Int(0).tag(config=True, sync=True)
        <traitlets.traitlets.Int object at ...>

        >   r   r   r   r   zcThe following attributes are set in using `tag`, but seem to be constructor keywords arguments: %s r   r   )r   keysintersectionr   UserWarningr   r   )r   r   Zmaybe_constructor_keywordsrM   rM   rN   tagU  s    zTraitType.tagc                 C   s
   t | jS rO   )reprr   r   rM   rM   rN   default_value_reprn  s    zTraitType.default_value_repr)N)N)N)NN)N)"rJ   rK   rL   r   r   ry   r"   r{   r   r   r   r   r   r>   r   r   r   r   rB   r   r   rW   r   r   r   r   r   r   r   r  r  r  r
  r  rM   rM   rM   rN   r:     s:   

?

 
	
N
r:   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	_CallbackWrapperzAn object adapting a on_trait_change callback into an observe callback.

    The comparison operator __eq__ is implemented to enable removal of wrapped
    callbacks.
    c                 C   sH   || _ t| j tjrdnd}tt|d | | _| jdkrDtdd S )Nr      z1a trait changed callback must have 0-4 arguments.)cbrv   types
MethodTyper   r   nargsr9   )r   r  offsetrM   rM   rN   r   ~  s
    
z_CallbackWrapper.__init__c                 C   s$   t |tr| j|jkS | j|kS d S rO   )rv   r  r  r   rM   rM   rN   __eq__  s    
z_CallbackWrapper.__eq__c                 C   s   | j dkr|   nv| j dkr,| |j n^| j dkrH| |j|j nB| j dkrh| |j|j|j n"| j dkr| |j|j|j|j d S )Nr   r   r      r  )r  r  r   r   oldr   r   rM   rM   rN   r     s    





z_CallbackWrapper.__call__N)rJ   rK   rL   r   r   r  r   rM   rM   rM   rN   r  w  s   r  c                 C   s   t | tr| S t| S d S rO   )rv   r  )r  rM   rM   rN   _callback_wrapper  s    
r  c                       s4   e Zd ZdZ fddZ fddZdd Z  ZS )r2   zA metaclass for HasDescriptors.

    This metaclass makes sure that any TraitType class attributes are
    instantiated and sets their name attribute.
    c                    sP   |  D ]4\}}t|rt|trtdtdd | ||< qt | |||S )z Create the HasDescriptors class.Traits should be given as instances, not types (for example, `Int()`, not `Int`). Passing types is deprecated in traitlets 4.1.r   r   )	itemsra   isclassrx   r:   r   ri   super__new__)mclsr   bases	classdictkvr   rM   rN   r    s    zMetaHasDescriptors.__new__c                    s   t  ||| | | dS )z-Finish initializing the HasDescriptors class.N)r  r   setup_class)rk   r   r  r   r#  rM   rN   r     s    zMetaHasDescriptors.__init__c                 C   sR   |  D ]\}}t|tr|| | qt| D ]\}}t|tr0||  q0dS )zSetup descriptor instance on the class

        This sets the :attr:`this_class` and :attr:`name` attributes of each
        BaseDescriptor in the class dict of the newly created ``cls`` before
        calling their :attr:`class_init` method.
        N)r  rv   r   r   r   r   )rk   r   r!  r"  _rM   rM   rN   r$    s    

zMetaHasDescriptors.setup_class)rJ   rK   rL   r   r  r   r$  __classcell__rM   rM   r#  rN   r2     s   r2   c                       s    e Zd ZdZ fddZ  ZS )r3   zA metaclass for HasTraits.c                    s   i | _ t | d S rO   )_trait_default_generatorsr  r$  )rk   r   r#  rM   rN   r$    s    zMetaHasTraits.setup_class)rJ   rK   rL   r   r$  r&  rM   rM   r#  rN   r3     s   r3   r   rw   c                 G   s@   |st d|D ]"}|turt|tst d| qt|| dS )a  A decorator which can be used to observe Traits on a class.

    The handler passed to the decorator will be called with one ``change``
    dict argument. The change dictionary at least holds a 'type' key and a
    'name' key, corresponding respectively to the type of notification and the
    name of the attribute that triggered the notification.

    Other keys may be passed depending on the value of 'type'. In the case
    where type is 'change', we also have the following keys:
    * ``owner`` : the HasTraits instance
    * ``old`` : the old value of the modified trait attribute
    * ``new`` : the new value of the modified trait attribute
    * ``name`` : the name of the modified trait attribute.

    Parameters
    ----------
    *names
        The str names of the Traits to observe on the object.
    type : str, kwarg-only
        The type of event to observe (e.g. 'change')
    z2Please specify at least one trait name to observe.z5trait names to observe must be strings or All, not %rr(  )rh   r   rv   r{   r5   )rw   r|   r   rM   rM   rN   rF     s    rF   c                    s   t t f fdd	}|S )aZ  Backward-compatibility shim decorator for observers

    Use with:

    @observe('name')
    @observe_compat
    def _foo_changed(self, change):
        ...

    With this, `super()._foo_changed(self, name, old, new)` in subclasses will still work.
    Allows adoption of new observer API without breaking subclasses that override and super.
    c                    sF   t |tr|}n,| jj}td||f t td|||| d} | |S )NzSA parent of %s._%s_changed has adopted the new (traitlets 4.1) @observe(change) APIr   )rw   r  r   r   r   )rv   dictr   rJ   r   ri   r   )r   Zchange_or_namer  r   r   clsnamefuncrM   rN   compatible_observer  s"    
z+observe_compat.<locals>.compatible_observer)r>   )r,  r-  rM   r+  rN   rG     s    rG   c                  G   s<   | st d| D ]"}|turt|tst d| qt| S )a  A decorator to register cross validator of HasTraits object's state
    when a Trait is set.

    The handler passed to the decorator must have one ``proposal`` dict argument.
    The proposal dictionary must hold the following keys:

    * ``owner`` : the HasTraits instance
    * ``value`` : the proposed value for the modified trait attribute
    * ``trait`` : the TraitType instance associated with the attribute

    Parameters
    ----------
    *names
        The str names of the Traits to validate.

    Notes
    -----
    Since the owner has access to the ``HasTraits`` instance via the 'owner' key,
    the registered cross validator could potentially make changes to attributes
    of the ``HasTraits`` instance. However, we recommend not to do so. The reason
    is that the cross-validation of attributes may run in arbitrary order when
    exiting the ``hold_trait_notifications`` context, and such changes may not
    commute.
    z3Please specify at least one trait name to validate.z6trait names to validate must be strings or All, not %r)rh   r   rv   r{   rA   )r|   r   rM   rM   rN   rI     s    rI   c                 C   s   t | tstd|  t| S )a,  A decorator which assigns a dynamic default for a Trait on a HasTraits object.

    Parameters
    ----------
    name
        The str name of the Trait on the object whose default should be generated.

    Notes
    -----
    Unlike observers and validators which are properties of the HasTraits
    instance, default value generators are class-level properties.

    Besides, default generators are only invoked if they are registered in
    subclasses of `this_type`.

    ::

        class A(HasTraits):
            bar = Int()

            @default('bar')
            def get_bar_default(self):
                return 11

        class B(A):
            bar = Float()  # This trait ignores the default generator defined in
                           # the base class A

        class C(B):

            @default('bar')
            def some_other_default(self):  # This default generator should not be
                return 3.0                 # ignored since it is defined in a
                                           # class derived from B.a.this_class.
    z*Trait name must be a string or All, not %r)rv   r{   rh   r!   )r   rM   rM   rN   rB   ;  s    $
rB   c                   @   s&   e Zd Zdd Zdd ZdddZdS )	r%   c                 C   s
   || _ | S rO   r+  )r   r,  rM   rM   rN   
_init_calle  s    zEventHandler._init_callc                 O   s.   t | dr| j|i |S | j|i |S dS )zCPass `*args` and `**kwargs` to the handler's function if it exists.r,  N)r   r,  r.  )r   r   r   rM   rM   rN   r   i  s    
zEventHandler.__call__Nc                 C   s   |d u r| S t | j|S rO   )r  r  r,  )r   instrk   rM   rM   rN   r   p  s    zEventHandler.__get__)N)rJ   rK   rL   r.  r   r   rM   rM   rM   rN   r%   d  s   r%   c                   @   s   e Zd Zdd Zdd ZdS )r5   c                 C   s   || _ || _d S rO   )trait_namesrw   )r   r|   rw   rM   rM   rN   r   w  s    zObserveHandler.__init__c                 C   s   |j | | j| jd d S )Nr(  )rF   r0  rw   r   r/  rM   rM   rN   r   {  s    zObserveHandler.instance_initNrJ   rK   rL   r   r   rM   rM   rM   rN   r5   v  s   r5   c                   @   s   e Zd Zdd Zdd ZdS )rA   c                 C   s
   || _ d S rO   r0  )r   r|   rM   rM   rN   r     s    zValidateHandler.__init__c                 C   s   | | | j d S rO   )_register_validatorr0  r1  rM   rM   rN   r     s    zValidateHandler.instance_initNr2  rM   rM   rM   rN   rA     s   rA   c                       s$   e Zd Zdd Z fddZ  ZS )r!   c                 C   s
   || _ d S rO   )r   r   r   rM   rM   rN   r     s    zDefaultHandler.__init__c                    s   t  || | |j| j< d S rO   )r  r   r'  r   r   r#  rM   rN   r     s    zDefaultHandler.class_init)rJ   rK   rL   r   r   r&  rM   rM   r#  rN   r!     s   r!   c                       s8   e Zd ZdZejejejd fddZdd Z  ZS )r+   z5The base class for all classes that have descriptors.)r   r   returnc                     s^   | d }| dd  } t t|j}|tju r4||}n||g| R i |}|j| i | |S r   )r  r+   r  r   setup_instance)r   r   rk   Znew_methr/  r#  rM   rN   r    s    

zHasDescriptors.__new__c               	   O   sh   | d }| dd } d|_ |j}t|D ]:}zt||}W n tyL   Y q(0 t|tr(|| q(dS )zD
        This is called **before** self.__init__ is called.
        r   r   NF)r   r   r   r   r   rv   r   r   )r   r   r   rk   rZ   r   rM   rM   rN   r7    s    
zHasDescriptors.setup_instance)	rJ   rK   rL   r   ry   r   r  r7  r&  rM   rM   r#  rN   r+     s   r+   )	metaclassc                       s  e Zd ZU ejeejf ed< ejeejf ed< ejeejf ed< eed<  fddZ	 fddZ
d	d
 Zdd Zeejdd Zejdd Zdd Zdd Zdd Zdd Zdd ZdFddZedfd d!Zedfd"d#Zefd$d%Zd&d' Zd(d) Zd*d+ Zed,d- Z ed.d/ Z!e fd0d1Z"d2d3 Z#d4d5 Z$d6d7 Z%d8d9 Z&d:d; Z'd<d= Z(d>d? Z)dGd@dAZ*e fdBdCZ+edHdDdEZ,  Z-S )Ir,   r   _trait_notifiersr   r   c                     sF   | d }| dd  } i |_ i |_i |_d|_tt|j| i | d S )Nr   r   F)r   r9  r   r   r  r,   r7  )r   r   r   r#  rM   rN   r7    s    zHasTraits.setup_instancec              
      s   |}i }|   B | D ](\}}| |r:t| || q|||< qW d    n1 sX0    Y  zt j|i | W n ty } zhdd |D }| D ]\}	}
||	 d|
 qd|}t	dj
|| jj|dtdd W Y d }~n
d }~0 0 d S )	Nc                 S   s   g | ]}t |qS rM   )r  )r   argrM   rM   rN   
<listcomp>  r   z&HasTraits.__init__.<locals>.<listcomp>=z, zPassing unrecognized arguments to super({classname}).__init__({arg_s}).
{error}
This is deprecated in traitlets 4.2.This error will be raised in a future release of traitlets.)arg_sr\   r  r   r   )hold_trait_notificationsr  	has_traitr   r  r   rh   r   r  r   r`   r   rJ   ri   )r   r   r   Z
super_argsZsuper_kwargsrZ   r   rp   Z
arg_s_listr!  r"  r=  r#  rM   rN   r     s.    

(
zHasTraits.__init__c                 C   s4   | j  }i |d< i |d< | j |d< d|d< |S )Nr9  r   r   Fr   )rc   r   r   )r   drM   rM   rN   __getstate__  s    
zHasTraits.__getstate__c              	   C   sX   |  | _| j}t|D ]:}zt||}W n ty<   Y q0 t|tr||  qd S rO   )	r   rc   r   r   r   r   rv   r%   r   )r   staterk   rZ   r   rM   rM   rN   __setstate__  s    

zHasTraits.__setstate__c                 c   s4   | j rdV  dS zd| _ dV  W d| _ nd| _ 0 dS )z
        A contextmanager for running a block with our cross validation lock set
        to True.

        At the end of the block, the lock's value is restored to its value
        prior to entering the block.
        NTF)r   r   rM   rM   rN   r     s    
zHasTraits.cross_validation_lockc                 #   sz  | j rdV  dS i  dd  fdd}zzR|| _d| _ dV  t  D ].}t| j|}|| t| |}| || qNW n ty } ztdd | _ 	 D ]L\}}|ddd	 D ]4}|j
d
kr|jtur| ||j q| j| qqi  |W Y d}~n
d}~0 0 W d| _ | `  D ]}|D ]}| | q,q$n2d| _ | `  D ]}|D ]}| | q^qV0 dS )aH  Context manager for bundling trait change notifications and cross
        validation.

        Use this when doing multiple trait assignments (init, config), to avoid
        race conditions in trait notifiers requesting other trait values.
        All trait notifications will fire after all values have been assigned.
        Nc                 S   sJ   | du r|gS | d d dkr8|j dkr8|j| d d< n
| | | S dS )z5Merges the provided change with the last if possible.Nr  rw   r   r   )rw   r   r   )Zpast_changesr   rM   rM   rN   compress+  s    
z4HasTraits.hold_trait_notifications.<locals>.compressc                    s   | j } ||  |< d S rO   )r   rW   )r   r   cacherD  rM   rN   hold7  s    z0HasTraits.hold_trait_notifications.<locals>.holdTc                 S   s   d S rO   rM   r   rM   rM   rN   r   H  r   z4HasTraits.hold_trait_notifications.<locals>.<lambda>r  r   F)r   notify_changelistr  r   r   r   	set_traitr9   r  rw   r  r>   r   popvalues)r   rG  r   r   r   rp   changesr   rM   rE  rN   r>    sD    	


z"HasTraits.hold_trait_notificationsc              	   C   s   |  t|||| dd d S )Nr   )r   r  r   r   rw   )rH  r   )r   r   r   r   rM   rM   rN   r   ]  s    zHasTraits._notify_traitc                 C   s
   |  |S )z"Notify observers of a change event)r   r   rM   rM   rN   rH  h  s    zHasTraits.notify_changec           	      C   sD  t |tst|}|j|j }}g }|| j|i |g  || j|i tg  || jti |g  || jti tg  d| }|jdkrt| |rt	| j
|}t |tst|| j
|d t	| |}||vr|t| |D ]D}t |tr|j}n$t |tr6|jdur6t	| |j}|| qdS )zNotify observers of any eventz_%s_changedr   z$use @observe and @unobserve instead.N)rv   r   r   rw   extendr9  rW   r   r   r   r   r5   rq   r   r  r  r   r%   )	r   eventr   rw   Z	callables
magic_nameclass_valuer  crM   rM   rN   r   l  s>    


zHasTraits._notify_observersc                 C   sd   || j vrg }||i| j |< n0|| j | vr@g }|| j | |< n| j | | }||vr`|| d S rO   )r9  r   )r   handlerr   rw   ZnlistrM   rM   rN   _add_notifiers  s    
zHasTraits._add_notifiersc                 C   sF   z.|d u r| j | |= n| j | | | W n ty@   Y n0 d S rO   )r9  remover   )r   rS  r   rw   rM   rM   rN   _remove_notifiers  s    zHasTraits._remove_notifiersNFc                 C   sH   t dtdd |du rt}|r2| jt||d n| jt||d dS )a  DEPRECATED: Setup a handler to be called when a trait changes.

        This is used to setup dynamic notifications of trait changes.

        Static handlers can be created by creating methods on a HasTraits
        subclass with the naming convention '_[traitname]_changed'.  Thus,
        to create static handler for the trait 'a', create the method
        _a_changed(self, name, old, new) (fewer arguments can be used, see
        below).

        If `remove` is True and `handler` is not specified, all change
        handlers for the specified name are uninstalled.

        Parameters
        ----------
        handler : callable, None
            A callable that is called when a trait changes.  Its
            signature can be handler(), handler(name), handler(name, new),
            handler(name, old, new), or handler(name, old, new, self).
        name : list, str, None
            If None, the handler will apply to all traits.  If a list
            of str, handler will apply to all names in the list.  If a
            str, the handler will apply just to that name.
        remove : bool
            If False (the default), then install the handler.  If True
            then unintall it.
        zCon_trait_change is deprecated in traitlets 4.1: use observe insteadr   r   Nr   )r   ri   r   r   r  rF   )r   rS  r   rU  rM   rM   rN   on_trait_change  s    zHasTraits.on_trait_changer   c                 C   s$   t |}|D ]}| ||| qdS )a	  Setup a handler to be called when a trait changes.

        This is used to setup dynamic notifications of trait changes.

        Parameters
        ----------
        handler : callable
            A callable that is called when a trait changes. Its
            signature should be ``handler(change)``, where ``change`` is a
            dictionary. The change dictionary at least holds a 'type' key.
            * ``type``: the type of notification.
            Other keys may be passed depending on the value of 'type'. In the
            case where type is 'change', we also have the following keys:
            * ``owner`` : the HasTraits instance
            * ``old`` : the old value of the modified trait attribute
            * ``new`` : the new value of the modified trait attribute
            * ``name`` : the name of the modified trait attribute.
        names : list, str, All
            If names is All, the handler will apply to all traits.  If a list
            of str, handler will apply to all names in the list.  If a
            str, the handler will apply just to that name.
        type : str, All (default: 'change')
            The type of notification to filter by. If equal to All, then all
            notifications are passed to the observe handler.
        N)rH   rT  r   rS  r|   rw   r}   rM   rM   rN   rF     s    zHasTraits.observec                 C   s$   t |}|D ]}| ||| qdS )a  Remove a trait change handler.

        This is used to unregister handlers to trait change notifications.

        Parameters
        ----------
        handler : callable
            The callable called when a trait attribute changes.
        names : list, str, All (default: All)
            The names of the traits for which the specified handler should be
            uninstalled. If names is All, the specified handler is uninstalled
            from the list of notifiers corresponding to all changes.
        type : str or All (default: 'change')
            The type of notification to filter by. If All, the specified handler
            is uninstalled from the list of notifiers corresponding to all types.
        N)rH   rV  rX  rM   rM   rN   r     s    zHasTraits.unobservec                 C   s4   |t u ri | _n z| j|= W n ty.   Y n0 dS )zRemove trait change handlers of any type for the specified name.
        If name is not specified, removes all trait notifiers.N)r   r9  r   r5  rM   rM   rN   unobserve_all
  s    zHasTraits.unobserve_allc                 C   sZ   |D ]<}d| }t | |rt| j|}t|tst|| j|d q|D ]}|| j|< qFdS )a  Setup a handler to be called when a trait should be cross validated.

        This is used to setup dynamic notifications for cross-validation.

        If a validator is already registered for any of the provided names, a
        TraitError is raised and no new validator is registered.

        Parameters
        ----------
        handler : callable
            A callable that is called when the given trait is cross-validated.
            Its signature is handler(proposal), where proposal is a Bunch (dictionary with attribute access)
            with the following attributes/keys:
                * ``owner`` : the HasTraits instance
                * ``value`` : the proposed value for the modified trait attribute
                * ``trait`` : the TraitType instance associated with the attribute
        names : List of strings
            The names of the traits that should be cross-validated
        r   r   N)r   r   r   rv   rA   rq   r   )r   rS  r|   r   rP  rQ  rM   rM   rN   r4    s    

zHasTraits._register_validatorc                 K   s\   | j }d|ji}t|dr$|j|d< || t|j|f|| _ | D ]}||  qHdS )z;Dynamically add trait attributes to the HasTraits instance.rK   rL   N)	r   rK   r   rL   r   rw   rJ   rL  r   )r   r   rk   attrsr   rM   rM   rN   
add_traits7  s    



zHasTraits.add_traitsc                 C   s>   | j }| |s(td|j d| nt||| | dS )z>Forcibly sets trait attribute, including read-only attributes.Class  does not have a trait named N)r   r?  r9   rJ   r   r   )r   r   r   rk   rM   rM   rN   rJ  C  s    
zHasTraits.set_traitc                 K   s   t | jf i |S )zGet a list of all the names of this class' traits.

        This method is just like the :meth:`trait_names` method,
        but is unbound.
        )rI  class_traitsrk   r   rM   rM   rN   class_trait_namesK  s    zHasTraits.class_trait_namesc                 K   s   t dd t| D }t|dkr&|S i }| D ]H\}}| D ].\}}t|sZt|}||j|dsB q2qB|||< q2|S )a  Get a ``dict`` of all the traits of this class.  The dictionary
        is keyed on the name and the values are the TraitType objects.

        This method is just like the :meth:`traits` method, but is unbound.

        The TraitTypes returned don't know anything about the values
        that the various HasTrait's instances are holding.

        The metadata kwargs allow functions to be passed in which
        filter traits based on metadata values.  The functions should
        take a single value as an argument and return a boolean.  If
        any function returns False, then the trait is not included in
        the output.  If a metadata key doesn't exist, None will be passed
        to the function.
        c                 S   s   g | ]}t |d  tr|qS r   rv   r:   r   ZmembrM   rM   rN   r;  e  r   z*HasTraits.class_traits.<locals>.<listcomp>r   N)r)  r   r   r  callabler~   r   rW   )rk   r   r   resultr   r   	meta_name	meta_evalrM   rM   rN   r^  T  s    
zHasTraits.class_traitsc                    s,   t | |   fdd| jf i | D S )zGet a dict of all the traitlets defined on this class, not a parent.

        Works like `class_traits`, except for excluding traits from parents.
        c                    s&   i | ]\}}t  |d |ur||qS rO   r   )r   r}   ry   suprM   rN   
<dictcomp>}  s   z.HasTraits.class_own_traits.<locals>.<dictcomp>)r  r^  r  r_  r#  ri  rN   class_own_traitsv  s    

zHasTraits.class_own_traitsc                 C   s   t t| j|dtS )z?Returns True if the object has a trait with the specified name.N)rv   r   r   r:   r5  rM   rM   rN   r?    s    zHasTraits.has_traitc                 C   s
   || j v S )a'  Returns True if the specified trait has a value.

        This will return false even if ``getattr`` would return a
        dynamically generated default value. These default values
        will be recognized as existing only after they have been
        generated.

        Example

        .. code-block:: python

            class MyClass(HasTraits):
                i = Int()

            mc = MyClass()
            assert not mc.trait_has_value("i")
            mc.i # generates a default value
            assert mc.trait_has_value("i")
        )r   r5  rM   rM   rN   trait_has_value  s    zHasTraits.trait_has_valuec                    s    fdd j f i |D S )a  A ``dict`` of trait names and their values.

        The metadata kwargs allow functions to be passed in which
        filter traits based on metadata values.  The functions should
        take a single value as an argument and return a boolean.  If
        any function returns False, then the trait is not included in
        the output.  If a metadata key doesn't exist, None will be passed
        to the function.

        Returns
        -------
        A ``dict`` of trait names and their values.

        Notes
        -----
        Trait values are retrieved via ``getattr``, any exceptions raised
        by traits or the operations they may trigger will result in the
        absence of a trait value in the result ``dict``.
        c                    s   i | ]}|t  |qS rM   rh  )r   r   r   rM   rN   rk    r   z*HasTraits.trait_values.<locals>.<dictcomp>r3  r   r   rM   r   rN   trait_values  s    zHasTraits.trait_valuesc                 C   s   d| }|| j v rt| |S | j}t||}t|ts:J | }z|d||jd  }W n typ   Y n0 |D ]<}||j v rt||  S ||j 	di v rv|j
|   S qv|jS )zReturn default generator for a given trait

        Walk the MRO to resolve the correct default generator according to inheritance.
        z_%s_defaultNr   r'  )rc   r   r   rv   r:   mroindexr   rt   rW   r'  rB   )r   r   r]   rk   r   rp  rR  rM   rM   rN   _get_trait_default_generator  s"    



z&HasTraits._get_trait_default_generatorc                 O   s   |D ]*}|  |std| dt| j dqt|dkrZt|dkrZ| |d | S | jf i |}|| i }|D ]}| || ||< q||S )zReturn a trait's default value or a dictionary of them

        Notes
        -----
        Dynamically generated default values may
        depend on the current state of the object.'z' is not a trait of 'z' instancesr   r   )r?  r9   rw   rJ   r   rr  r0  rN  )r   r|   r   r}   r0  defaultsrM   rM   rN   r     s    

zHasTraits.trait_defaultsc                 K   s   t | jf i |S )z2Get a list of all the names of this class' traits.)rI  r   rn  rM   rM   rN   r0    s    zHasTraits.trait_namesc                 K   s   t dd t| jD }t|dkr(|S i }| D ]H\}}| D ].\}}t|s\t|}||j|dsD q4qD|||< q4|S )a  Get a ``dict`` of all the traits of this class.  The dictionary
        is keyed on the name and the values are the TraitType objects.

        The TraitTypes returned don't know anything about the values
        that the various HasTrait's instances are holding.

        The metadata kwargs allow functions to be passed in which
        filter traits based on metadata values.  The functions should
        take a single value as an argument and return a boolean.  If
        any function returns False, then the trait is not included in
        the output.  If a metadata key doesn't exist, None will be passed
        to the function.
        c                 S   s   g | ]}t |d  tr|qS ra  rb  rc  rM   rM   rN   r;    r   z$HasTraits.traits.<locals>.<listcomp>r   N)	r)  r   r   r   r  rd  r~   r   rW   )r   r   r   re  r   r   rf  rg  rM   rM   rN   r     s    
zHasTraits.traitsc                 C   s   zt | j|}W n* ty:   td| jj d| Y n0 d| d }t| |rr|t | |v rrt | |||S |j||S dS )z%Get metadata values for trait by key.r\  r]  r%  	_metadataN)r   r   r   r9   rJ   r   rW   r   )r   Z	traitnamerZ   rB   r   metadata_namerM   rM   rN   trait_metadata  s    
zHasTraits.trait_metadatac                    s&   t | |   fdd| | D S )zGet a dict of all event handlers defined on this class, not a parent.

        Works like ``event_handlers``, except for excluding traits from parents.
        c                    s&   i | ]\}}t  |d |ur||qS rO   rh  )r   r}   rp   ri  rM   rN   rk    s   z4HasTraits.class_own_trait_events.<locals>.<dictcomp>)r  eventsr  )rk   r   r#  ri  rN   class_own_trait_events  s    

z HasTraits.class_own_trait_eventsc                 C   sn   i }t | D ]\\}}t|tr|du r0|||< q||jv rD|||< qt|dr| jf i |jr|||< q|S )a  Get a ``dict`` of all the event handlers of this class.

        Parameters
        ----------
        name : str (default: None)
            The name of a trait of this class. If name is ``None`` then all
            the event handlers of this class will be returned instead.

        Returns
        -------
        The event handlers associated with a trait name, or all event handlers.
        Ntags)r   rv   r%   r0  r   rz  )rk   r   rx  r!  r"  rM   rM   rN   trait_events"  s    





zHasTraits.trait_events)NNF)N)N).rJ   rK   rL   ry   r"   r{   r   r   r   r7  r   rA  rC  propertyr   r   r   r>  r   rH  r   rT  rV  rW  r   rF   r   rY  r4  r[  rJ  classmethodr`  r^  rl  r?  rm  ro  rr  r   r0  r   rw  ry  r{  r&  rM   rM   r#  rN   r,     sV   
!
@-	
("

!!
r,   c                   @   s   e Zd ZdZdd ZdS )r   ze
    A trait with error reporting and string -> type resolution for Type,
    Instance and This.
    c                 C   s   t |S )zM
        Resolve a string supplied for a type into an actual object.
        r   )r   stringrM   rM   rN   _resolve_stringL  s    z#ClassBasedTraitType._resolve_stringNrJ   rK   rL   r   r  rM   rM   rM   rN   r   F  s   r   c                       sR   e Zd ZdZedf fdd	Zdd Zdd Z fd	d
Zdd Z	dd Z
  ZS )r<   z<A trait whose value must be a subclass of a specified class.Nc                    sz   |t u r|du rtn|}n|}|du r@|du s6|t u r<t}n|}t|s\t|ts\td|| _t j	|fi | dS )a^  Construct a Type trait

        A Type trait specifies that its values must be subclasses of
        a particular class.

        If only ``default_value`` is given, it is used for the ``klass`` as
        well. If neither are given, both default to ``object``.

        Parameters
        ----------
        default_value : class, str or None
            The default value must be a subclass of klass.  If an str,
            the str must be a fully specified class name, like 'foo.bar.Bah'.
            The string is resolved into real class, when the parent
            :class:`HasTraits` class is instantiated.
        klass : class, str [ default object ]
            Values of this trait must be a subclass of klass.  The klass
            may be specified in a string like: 'foo.bar.MyClass'.
            The string is resolved into real class, when the parent
            :class:`HasTraits` class is instantiated.
        allow_none : bool [ default False ]
            Indicates whether None is allowed as an assignable value.
        **kwargs
            extra kwargs passed to `ClassBasedTraitType`
        Nz"A Type trait must specify a class.)
r>   r   ra   r  rv   r{   r9   klassr  r   )r   r   r  r   Znew_default_valuer#  rM   rN   r   V  s    zType.__init__c                 C   sz   t |tr@z| |}W n& ty>   td| j||f Y n0 zt|| jrT|W S W n tyh   Y n0 | 	|| dS )z4Validates that the value is a valid object instance.zJThe '%s' trait of %s instance must be a type, but %r could not be importedN)
rv   r{   r  ImportErrorr9   r   rx   r  r   r  r   rM   rM   rN   rI     s    



zType.validatec                 C   sB   t | jtr| j}n| jjd | jj }d| }| jr>|d S |S )#Returns a description of the trait.r_   za subclass of '%s' or None)rv   r  r{   rK   rJ   r   )r   r  re  rM   rM   rN   r     s    z	Type.infoc                    s   |    t | d S rO   _resolve_classesr  r   r   r#  rM   rN   r     s    zType.instance_initc                 C   s8   t | jtr| | j| _t | jtr4| | j| _d S rO   )rv   r  r{   r  r   r   rM   rM   rN   r    s    zType._resolve_classesc                 C   s>   | j }|d usJ t|tr$t|S t|j d|j S d S )Nr_   )r   rv   r{   r  rK   rJ   r   rM   rM   rN   r    s
    
zType.default_value_repr)rJ   rK   rL   r   r>   r   rI   r   r   r  r  r&  rM   rM   r#  rN   r<   S  s   ,r<   c                       sb   e Zd ZdZdZd fdd	Zdd Zdd Z fd	d
Zdd Z	dd Z
dd Zdd Z  ZS )r-   zA trait whose value must be an instance of a specified class.

    The value can also be an instance of a subclass of the specified class.

    Subclasses can declare default classes by overriding the klass attribute
    Nc                    s   |du r| j }|dur2t|s*t|tr2|| _ ntd| |durXt|tsXtd|durrt|tsrtd|| _|| _	t
 jf i | dS )a  Construct an Instance trait.

        This trait allows values that are instances of a particular
        class or its subclasses.  Our implementation is quite different
        from that of enthough.traits as we don't allow instances to be used
        for klass and we handle the ``args`` and ``kw`` arguments differently.

        Parameters
        ----------
        klass : class, str
            The class that forms the basis for the trait.  Class names
            can also be specified as strings, like 'foo.bar.Bar'.
        args : tuple
            Positional arguments for generating the default value.
        kw : dict
            Keyword arguments for generating the default value.
        allow_none : bool [ default False ]
            Indicates whether None is allowed as a value.
        **kwargs
            Extra kwargs passed to `ClassBasedTraitType`

        Notes
        -----
        If both ``args`` and ``kw`` are None, then the default value is None.
        If ``args`` is a tuple and ``kw`` is a dict, then the default is
        created as ``klass(*args, **kw)``.  If exactly one of ``args`` or ``kw`` is
        None, the None is replaced by ``()`` or ``{}``, respectively.
        Nz+The klass attribute must be a class not: %rz)The 'kw' argument must be a dict or None.z,The 'args' argument must be a tuple or None.)r  ra   r  rv   r{   r9   r)  r   default_argsdefault_kwargsr  r   )r   r  r   kwr   r#  rM   rN   r     s    zInstance.__init__c                 C   s.   | j d usJ t|| j r|S | || d S rO   )r  rv   r  r   rM   rM   rN   rI     s    zInstance.validatec                 C   s6   t | jtrt| j}ntd| j}| jr2|d7 }|S )Nr   r  )rv   r  r{   r   r	   r   )r   re  rM   rM   rN   r     s    zInstance.infoc                    s   |    t | d S rO   r  r   r#  rM   rN   r     s    zInstance.instance_initc                 C   s   t | jtr| | j| _d S rO   )rv   r  r{   r  r   rM   rM   rN   r    s    zInstance._resolve_classesc                 C   sB   | j d u r| jd u rd S | jd us&J | j| j p2di | jp<i S )NrM   )r  r  r  r   rM   rM   rN   r     s    zInstance.make_dynamic_defaultc                 C   s   t |  S rO   )r  r   r   rM   rM   rN   r    s    zInstance.default_value_reprc                 C   s   t |S rO   )ru   r   rM   rM   rN   r     s    zInstance.from_string)NNN)rJ   rK   rL   r   r  r   rI   r   r   r  r   r  r   r&  rM   rM   r#  rN   r-     s   /	r-   c                   @   s   e Zd ZdZdd ZdS )r(   zC
    Mixin for forward-declared versions of Instance and Type.
    c                 C   s   | j j}td||gS )z
        Find the specified class name by looking for it in the module in which
        our this_class attribute was defined.
        r_   )r   rK   r   r  )r   r~  modnamerM   rM   rN   r    s    z$ForwardDeclaredMixin._resolve_stringNr  rM   rM   rM   rN   r(     s   r(   c                   @   s   e Zd ZdZdS )r)   z+
    Forward-declared version of Type.
    NrJ   rK   rL   r   rM   rM   rM   rN   r)      s   r)   c                   @   s   e Zd ZdZdS )r'   z/
    Forward-declared version of Instance.
    Nr  rM   rM   rM   rN   r'   (  s   r'   c                       s,   e Zd ZdZdZ fddZdd Z  ZS )r8   a  A trait for instances of the class containing this trait.

    Because how how and when class bodies are executed, the ``This``
    trait can only have a default value of None.  This, and because we
    always validate default values, ``allow_none`` is *always* true.
    z4an instance of the same type as the receiver or Nonec                    s   t  jdi | d S )N)Nr  r   )r   r   r#  rM   rN   r   :  s    zThis.__init__c                 C   s6   | j d usJ t|| j s"|d u r&|S | || d S rO   )r   rv   r  r   rM   rM   rN   rI   =  s    zThis.validate)rJ   rK   rL   r   r   r   rI   r&  rM   rM   r#  rN   r8   0  s   r8   c                       sb   e Zd ZdZ fddZd fdd	Z fddZ fd	d
Zdd Zdd Z	 fddZ
  ZS )r?   z'A trait type representing a Union type.c                    s8   t || _ddd | jD | _t jf i | dS )a  Construct a Union  trait.

        This trait allows values that are allowed by at least one of the
        specified trait types. A Union traitlet cannot have metadata on
        its own, besides the metadata of the listed types.

        Parameters
        ----------
        trait_types : sequence
            The list of trait types of length at least 1.
        **kwargs
            Extra kwargs passed to `TraitType`

        Notes
        -----
        Union([Float(), Bool(), Int()]) attempts to validate the provided values
        with the validation function of Float, then Bool, and finally Int.

        Parsing from string is ambiguous for container types which accept other
        collection-like literals (e.g. List accepting both `[]` and `()`
        precludes Union from ever parsing ``Union([List(), Tuple()])`` as a tuple;
        you can modify behaviour of too permissive container traits by overriding
        ``_literal_from_string_pairs`` in subclasses.
        Similarly, parsing unions of numeric types is only unambiguous if
        types are provided in order of increasing permissiveness, e.g.
        ``Union([Int(), Float()])`` (since floats accept integer-looking values).
        z or c                 S   s   g | ]}|  qS rM   )r   )r   ttrM   rM   rN   r;  h  r   z"Union.__init__.<locals>.<listcomp>N)rI  r   r  r   r  r   )r   r   r   r#  rM   rN   r   K  s    
zUnion.__init__Nc                    s4   t  |}| jD ]}|tu r*||}q q0q|S rO   )r  rB   r   r>   )r   r   rB   r   r#  rM   rN   rB   k  s    
zUnion.defaultc                    s.   t | jD ]}||d  q
t || d S rO   )reversedr   r   r  )r   rk   r   
trait_typer#  rM   rN   r   t  s    zUnion.class_initc                    s*   t | jD ]}|| q
t | d S rO   )r  r   r   r  )r   r   r  r#  rM   rN   r   y  s    zUnion.instance_initc              
   C   s   |j z | jD ]b}zF|||}| jd urBt|d| j d |j |W   W  d    S  tyn   Y qY q0 qW d    n1 s0    Y  | || d S )Nr%  ru  )r   r   r   r   r   r   r9   r  )r   r   r   r  r"  rM   rM   rN   rI   ~  s    

*zUnion.validatec                 C   s.   t |trt| j|j S t| j|g S d S rO   r   r   rM   rM   rN   r     s    
zUnion.__or__c              
      sP   | j D ]<}z||}|d |W   S  ttfy@   Y qY q0 qt |S rO   )r   r   rI   r9   rt   r  )r   rS   r  r"  r#  rM   rN   r     s    

zUnion.from_string)N)rJ   rK   rL   r   r   rB   r   r   rI   r   r   r&  rM   rM   r#  rN   r?   H  s    	r?   c                   @   s.   e Zd ZU dZdZejej ed< dZ	dZ
dS )r   zA trait which allows any value.Nr   Tr   )rJ   rK   rL   r   r   ry   r   r   r   r   r   rM   rM   rM   rN   r     s   
r   c                 C   sh   | j dur2|| j k r2tdj| jt||| j d| jdurd|| jkrdtdj| jt||| jd|S )z
    Validate that a number to be applied to a trait is between bounds.

    If value is not between min_bound and max_bound, this raises a
    TraitError with an error message appropriate for this trait.
    Nz}The value of the '{name}' trait of {klass} instance should not be less than {min_bound}, but a value of {value} was specified)r   r  r   Z	min_boundzThe value of the '{name}' trait of {klass} instance should not be greater than {max_bound}, but a value of {value} was specified)r   r  r   Z	max_bound)minr9   r`   r   r   max)r   r   r   rM   rM   rN   _validate_bounds  s    r  c                       s>   e Zd ZdZdZdZedf fdd	Zdd Zd	d
 Z	  Z
S )r.   zAn int trait.r   zan intFc                    s8   | dd | _| dd | _t jf ||d| d S )Nr  r  r   r   )rK  r  r  r  r   r   r   r   r   r#  rM   rN   r     s    zInt.__init__c                 C   s"   t |ts| || t| ||S rO   )rv   intr  r  r   rM   rM   rN   rI     s    
zInt.validatec                 C   s   | j r|dkrd S t|S Nr   )r   r  r   rM   rM   rN   r     s    zInt.from_stringrJ   rK   rL   r   r   r   r>   r   rI   r   r&  rM   rM   r#  rN   r.     s   r.   c                   @   s   e Zd ZdZdd ZdS )r   z#A casting version of the int trait.c                 C   s8   zt |}W n ty*   | || Y n0 t| ||S rO   )r  r   r  r  r   rM   rM   rN   rI     s
    zCInt.validateNrJ   rK   rL   r   rI   rM   rM   rM   rN   r     s   r   c                       s>   e Zd ZdZdZdZedf fdd	Zdd Zd	d
 Z	  Z
S )r&   zA float trait.g        za floatFc                    sB   | dtd | _| dtd| _t jf ||d| d S )Nr  infr  r  )rK  floatr  r  r  r   r  r#  rM   rN   r     s    zFloat.__init__c                 C   s4   t |trt|}t |ts(| || t| ||S rO   )rv   r  r  r  r  r   rM   rM   rN   rI     s
    

zFloat.validatec                 C   s   | j r|dkrd S t|S r  )r   r  r   rM   rM   rN   r     s    zFloat.from_stringr  rM   rM   r#  rN   r&     s   r&   c                   @   s   e Zd ZdZdd ZdS )r   z%A casting version of the float trait.c                 C   s8   zt |}W n ty*   | || Y n0 t| ||S rO   )r  r   r  r  r   rM   rM   rN   rI   	  s
    zCFloat.validateNr  rM   rM   rM   rN   r     s   r   c                   @   s(   e Zd ZdZdZdZdd Zdd ZdS )	r   zA trait for complex numbers.y                za complex numberc                 C   s4   t |tr|S t |ttfr$t|S | || d S rO   )rv   complexr  r  r  r   rM   rM   rN   rI   	  s
    
zComplex.validatec                 C   s   | j r|dkrd S t|S r  )r   r  r   rM   rM   rN   r   	  s    zComplex.from_stringNrJ   rK   rL   r   r   r   rI   r   rM   rM   rM   rN   r   
	  s
   r   c                   @   s   e Zd ZdZdd ZdS )r   z.A casting version of the complex number trait.c                 C   s.   z
t |W S  ty(   | || Y n0 d S rO   )r  r   r  r   rM   rM   rN   rI    	  s    
zCComplex.validateNr  rM   rM   rM   rN   r   	  s   r   c                   @   s(   e Zd ZdZdZdZdd Zdd ZdS )	r   zA trait for byte strings.r   za bytes objectc                 C   s   t |tr|S | || d S rO   )rv   bytesr  r   rM   rM   rN   rI   0	  s    
zBytes.validatec                 C   sz   | j r|dkrd S t|dkrpdD ]L}|d d d| kr"|d |kr"|}|dd }td||f t  qpq"|dS )	Nr   r  "rs  r   br  zZSupporting extra quotes around Bytes is deprecated in traitlets 5.0. Use %r instead of %r.utf8)r   r   r   FutureWarningencode)r   rS   quoteold_srM   rM   rN   r   5	  s    "zBytes.from_stringNr  rM   rM   rM   rN   r   *	  s
   r   c                   @   s   e Zd ZdZdd ZdS )r   z+A casting version of the byte string trait.c                 C   s.   z
t |W S  ty(   | || Y n0 d S rO   )r  r   r  r   rM   rM   rN   rI   J	  s    
zCBytes.validateNr  rM   rM   rM   rN   r   G	  s   r   c                   @   s(   e Zd ZdZdZdZdd Zdd ZdS )	r=   zA trait for unicode strings.r   za unicode stringc              
   C   sf   t |tr|S t |trVz|ddW S  tyT   d}t||| jt|Y n0 | 	|| d S )Nasciistrictz<Could not decode {!r} for unicode trait '{}' of {} instance.)
rv   r{   r  decodeUnicodeDecodeErrorr9   r`   r   r   r  )r   r   r   r^   rM   rM   rN   rI   W	  s    

zUnicode.validatec                 C   sz   | j r|dkrd S tj|}t|dkrvdD ]F}|d |d   krN|kr.n q.|}|dd }td||f t q.|S )Nr   r   r  r   r  r   zSupporting extra quotes around strings is deprecated in traitlets 5.0. You can use %r instead of %r if you require traitlets >=5.)r   rU   path
expanduserr   r   r  )r   rS   rR  r  rM   rM   rN   r   b	  s     zUnicode.from_stringNr  rM   rM   rM   rN   r=   Q	  s
   r=   c                   @   s   e Zd ZdZdd ZdS )r   z'A casting version of the unicode trait.c                 C   s.   z
t |W S  ty(   | || Y n0 d S rO   )r{   r   r  r   rM   rM   rN   rI   w	  s    
zCUnicode.validateNr  rM   rM   rM   rN   r   t	  s   r   c                   @   s0   e Zd ZdZdZedd Zdd Zdd Zd	S )
r4   z{A string holding a valid object name in this version of Python.

    This does not check that the name exists in any scope.z#a valid object identifier in Pythonc                 C   s   |S rO   rM   )r%  rS   rM   rM   rN   r   	  r   zObjectName.<lambda>c                 C   s2   |  ||}t|tr"t|r"|S | || d S rO   )
coerce_strrv   r{   rQ   r  r   rM   rM   rN   rI   	  s    zObjectName.validatec                 C   s   | j r|dkrd S |S r  r   r   rM   rM   rN   r   	  s    zObjectName.from_stringN)	rJ   rK   rL   r   r   staticmethodr  rI   r   rM   rM   rM   rN   r4   ~	  s
   r4   c                   @   s   e Zd ZdZdd ZdS )r#   zFA string holding a valid dotted object name in Python, such as A.b3._cc                 C   sB   |  ||}t|tr2tdd |dD r2|S | || d S )Nc                 s   s   | ]}t |V  qd S rO   rP   )r   r   rM   rM   rN   r   	  r   z,DottedObjectName.validate.<locals>.<genexpr>r_   )r  rv   r{   allrd   r  r   rM   rM   rN   rI   	  s    "zDottedObjectName.validateNr  rM   rM   rM   rN   r#   	  s   r#   c                   @   s(   e Zd ZdZdZdZdd Zdd ZdS )	r   zA boolean (True, False) trait.Fz	a booleanc                 C   s@   t |tr|S t |tr0|dkr$dS |dkr0dS | || d S )Nr   Tr   F)rv   r   r  r  r   rM   rM   rN   rI   	  s    

zBool.validatec                 C   s>   | j r|dkrd S | }|dv r&dS |dv r2dS tdd S )Nr   >   1trueT>   falserT   Fz%r is not 1, 0, true, or false)r   lowerrt   r   rM   rM   rN   r   	  s    zBool.from_stringNr  rM   rM   rM   rN   r   	  s
   
r   c                   @   s   e Zd ZdZdd ZdS )r   z'A casting version of the boolean trait.c                 C   s.   z
t |W S  ty(   | || Y n0 d S rO   )r   r   r  r   rM   rM   rN   rI   	  s    
zCBool.validateNr  rM   rM   rM   rN   r   	  s   r   c                       sX   e Zd ZdZef fdd	Zdd ZdddZdd	d
Zdd Z	dd Z
dd Z  ZS )r$   z0An enum whose value must be in a given sequence.c                    s6   || _ |ddr|tu rd }t j|fi | d S )Nr   F)rL  rW   r>   r  r   r   rL  r   r   r#  rM   rN   r   	  s    zEnum.__init__c                 C   s   || j v r|S | || d S rO   )rL  r  r   rM   rM   rN   rI   	  s    
zEnum.validateFc                 C   s0   | j }|r ddd |D }ntt|}|S )6Returns a description of the trait choices (not none).|c                 s   s   | ]}d | V  qdS z``%r``NrM   r   r   rM   rM   rN   r   	  r   z$Enum._choices_str.<locals>.<genexpr>)rL  r  r  rI  r   as_rstchoicesrM   rM   rN   _choices_str	  s
    zEnum._choices_strc                 C   s.   | j rd|rdnd nd}d| | | S r   or %s`None`r   r   any of r   r  r   r  nonerM   rM   rN   _info	  s    z
Enum._infoc                 C   s   | j ddS NFr  r  r   rM   rM   rN   r   	  s    z	Enum.infoc                 C   s   | j ddS NTr  r  r   rM   rM   rN   info_rst	  s    zEnum.info_rstc                 C   s.   z|  d |W S  ty(   t| Y S 0 d S rO   )rI   r9   ru   r   rM   rM   rN   r   	  s    zEnum.from_string)F)F)rJ   rK   rL   r   r>   r   rI   r  r  r   r  r   r&  rM   rM   r#  rN   r$   	  s   
	
r$   c                       sF   e Zd ZdZef fdd	Zdd ZdddZd	d
 Zdd Z	  Z
S )r   z4An enum of strings where the case should be ignored.c                    s   t  j|fd|i| d S Nr   r  r  r#  rM   rN   r   	  s    zCaselessStrEnum.__init__c                 C   sJ   t |ts| || | jD ]}| | kr|  S q| || d S rO   )rv   r{   r  rL  r  )r   r   r   r"  rM   rM   rN   rI   	  s    


zCaselessStrEnum.validateFc                 C   s0   | j rd|rdnd nd}d| | d| S )r  r  r  r   r   r  z (case-insensitive)r  r  rM   rM   rN   r  	  s    zCaselessStrEnum._infoc                 C   s   | j ddS r  r  r   rM   rM   rN   r   
  s    zCaselessStrEnum.infoc                 C   s   | j ddS r  r  r   rM   rM   rN   r  
  s    zCaselessStrEnum.info_rst)F)rJ   rK   rL   r   r>   r   rI   r  r   r  r&  rM   rM   r#  rN   r   	  s   	
r   c                       sR   e Zd ZdZdZdZeddf fdd	Zdd ZdddZ	d	d
 Z
dd Z  ZS )r*   zEAn case-ignoring enum matching choices by unique prefixes/substrings.Fc                    s(   || _ || _t j|fd|i| d S r  )case_sensitivesubstring_matchingr  r   )r   rL  r   r  r  r   r#  rM   rN   r   
  s    zFuzzyEnum.__init__c                    s   t ts| | | jr$dd ndd  | j}|r>dd ndd  | j} fdd|D }t|dkrt||D ]\}}|r|  S q| | d S )	Nc                 S   s   | S rO   rM   rR  rM   rM   rN   r    
  r   z$FuzzyEnum.validate.<locals>.<lambda>c                 S   s   |   S rO   )r  r  rM   rM   rN   r    
  r   c                 S   s   | |v S rO   rM   r"  rR  rM   rM   rN   r   #
  r   c                 S   s
   | | S rO   )
startswithr  rM   rM   rN   r   %
  r   c                    s   g | ]} |qS rM   rM   )r   rR  Z	conv_func
match_funcr   rM   rN   r;  )
  r   z&FuzzyEnum.validate.<locals>.<listcomp>r   )rv   r{   r  r  r  rL  sumzip)r   r   r   r  r  matchesr"  mrM   r  rN   rI   
  s     


zFuzzyEnum.validatec                 C   sV   | j rd|rdnd nd}| jr$dnd}| jr2dnd}d	| d
| d| | | S )r  r  r  r   r   Z	sensitiveZinsensitiveZ	substringprefixz	any case- r   )r   r  r  r  )r   r  r  casesubstrrM   rM   rN   r  1
  s    zFuzzyEnum._infoc                 C   s   | j ddS r  r  r   rM   rM   rN   r   8
  s    zFuzzyEnum.infoc                 C   s   | j ddS r  r  r   rM   rM   rN   r  ;
  s    zFuzzyEnum.info_rst)F)rJ   rK   rL   r   r  r  r>   r   rI   r  r   r  r&  rM   rM   r#  rN   r*   	
  s   
r*   c                       s   e Zd ZU dZdZejejeej	ej
 f  ed< dZej
ed< eZdZdZej
ed< def fdd		Z fd
dZdd Z fddZ fddZdd Zdd ZdddZ  ZS )r    z\An instance of a container (list, set, etc.)

    To be subclassed by overriding klass.
    Nr  rM   _cast_types)[]()_literal_from_string_pairsc                    s  |dur |t u r t|s |}d}|du rR|ddsRtd| jj dtdd t }|t u r`d}nB|du rvd}d|d	< n,t|| jr|f}nt	d
| jj d| t|rt|t
rtdtdd t|t
r| n|| _n|durt	dt| t jf | j|d| dS )a  Create a container trait type from a list, set, or tuple.

        The default value is created by doing ``List(default_value)``,
        which creates a copy of the ``default_value``.

        ``trait`` can be specified, which restricts the type of elements
        in the container to that TraitType.

        If only one arg is given and it is not a Trait, it is taken as
        ``default_value``:

        ``c = List([1, 2, 3])``

        Parameters
        ----------
        trait : TraitType [ optional ]
            the type for restricting the contents of the Container.  If unspecified,
            types are not checked.
        default_value : SequenceType [ optional ]
            The default value for the Trait.  Must be list/tuple/set, and
            will be cast to the container type.
        allow_none : bool [ default False ]
            Whether to allow the value to be None
        **kwargs : any
            further keys for extensions to the Trait (e.g. config)

        Nr   FSpecifying a(default_value=None) for no default is deprecated in traitlets 5.0.5. Use default_value=Undefinedr   r   rM   r   default value of  was r  r  z'`trait` must be a Trait or None, got %sr  r   )r>   rz   rW   r   r   rJ   ri   rv   _valid_defaultsrh   rw   _traitr
   r  r   r  )r   r   r   r   r   r#  rM   rN   r   K
  s:    

zContainer.__init__c                    sN   t || jr$| jd usJ | |}t ||}|d u r>|S | ||}|S rO   )rv   r  r  r  rI   validate_elementsr   r#  rM   rN   rI   
  s    
zContainer.validatec                 C   s   g }| j d u st| j tr|S |D ]T}z| j ||}W n2 tyj } z| ||| W Y d }~q"d }~0 0 || q"| jd usJ | |S rO   )r  rv   r   r   r9   r  r   r  )r   r   r   	validatedr"  r  rM   rM   rN   r  
  s    $zContainer.validate_elementsc                    s,   t | jtr| j|d  t || d S rO   )rv   r  r:   r   r  r   r#  rM   rN   r   
  s    zContainer.class_initc                    s(   t | jtr| j| t | d S rO   )rv   r  r:   r   r  r   r#  rM   rN   r   
  s    zContainer.instance_initc                 C   sH   t |tstd|zt|}W n ty:   d}Y n0 | d|S )Load value from a single stringzExpected string, got N)rv   r{   r9   r   r   rI   r   rS   r   rM   rM   rN   r   
  s    

zContainer.from_stringc                    s   j dusJ t|dkr|d dkr4jr4dS tdkrtfddjD rjrljjd }nd	}jdus~J td
	|j t
  tS tj}d|jv rj ndfdd	   fddt|D S )ziReturn the value from a list of config strings

        This is where we parse CLI configuration
        Nr   r   r   r   c                 3   s&   | ]\}}  |o |V  qd S rO   )r  endswith)r   startend)rrM   rN   r   
  s   z-Container.from_string_list.<locals>.<genexpr>r_   r   z}--{0}={1} for containers is deprecated in traitlets 5.0. You can pass `--{0} item` ... multiple times to add items to a list.rq  c                    s
     | S rO   item_from_string)rS   rq  r   rM   rN   r   
  r   z,Container.from_string_list.<locals>.<lambda>c                    s   g | ]\}} ||d qS ))rq  rM   )r   idxrS   r  rM   rN   r;  
  r   z.Container.from_string_list.<locals>.<listcomp>)N)r  r   r   anyr  r   rJ   r   r   r`   r  r   ra   	signaturer  
parameters	enumerate)r   s_listr*  sigrM   )r  r  r   rN   from_string_list
  s4    

zContainer.from_string_listc                 C   s   | j r| j |S |S dS )iCast a single item from a string

        Evaluated when parsing CLI configuration from a string
        N)r  r   r   rS   rq  rM   rM   rN   r  
  s    zContainer.item_from_string)N)rJ   rK   rL   r   r  ry   r   r?   r{   r<   r   r   r  SequenceTypesr  r  r  r>   r   rI   r  r   r   r   r  r  r&  rM   rM   r#  rN   r    ?
  s   
$H
'r    c                       sb   e Zd ZU dZeZefZej	e
d< dedejf fdd	Zdd Z fd	d
Z fddZ  ZS )r0   zAn instance of a Python list.r  Nr   c                    s(   || _ || _t jf ||d| dS )a  Create a List trait type from a list, set, or tuple.

        The default value is created by doing ``list(default_value)``,
        which creates a copy of the ``default_value``.

        ``trait`` can be specified, which restricts the type of elements
        in the container to that TraitType.

        If only one arg is given and it is not a Trait, it is taken as
        ``default_value``:

        ``c = List([1, 2, 3])``

        Parameters
        ----------
        trait : TraitType [ optional ]
            the type for restricting the contents of the Container.
            If unspecified, types are not checked.
        default_value : SequenceType [ optional ]
            The default value for the Trait.  Must be list/tuple/set, and
            will be cast to the container type.
        minlen : Int [ default 0 ]
            The minimum length of the input list
        maxlen : Int [ default sys.maxsize ]
            The maximum length of the input list
        )r   r   N)_minlen_maxlenr  r   r   r   r   Zminlenmaxlenr   r#  rM   rN   r   
  s    "zList.__init__c                 C   s(   d| j t|| j| j|f }t|d S )Nz_The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified.)r   r   r  r  r9   )r   r   r   rp   rM   rM   rN   length_error  s
    zList.length_errorc                    s6   t |}|| jk s|| jkr(| || t ||S rO   )r   r  r  r  r  r  )r   r   r   lengthr#  rM   rN   r  &  s    zList.validate_elementsc                    s,   t |trt ||gS t ||S d S rO   )rv   r{   r  r   r   r#  rM   rN   r   -  s    
zList.set)rJ   rK   rL   r   rI  r  r   r  ry   r   r   r>   sysmaxsizer   r  r  r   r&  rM   rM   r#  rN   r0   
  s   
&r0   c                       sD   e Zd ZdZeZeefZdZ	de
dejf fdd	Zdd Z  ZS )	r6   zAn instance of a Python set.)r  r  z{}Nr   c                    s   t  j||||fi | dS )a  Create a Set trait type from a list, set, or tuple.

        The default value is created by doing ``set(default_value)``,
        which creates a copy of the ``default_value``.

        ``trait`` can be specified, which restricts the type of elements
        in the container to that TraitType.

        If only one arg is given and it is not a Trait, it is taken as
        ``default_value``:

        ``c = Set({1, 2, 3})``

        Parameters
        ----------
        trait : TraitType [ optional ]
            the type for restricting the contents of the Container.
            If unspecified, types are not checked.
        default_value : SequenceType [ optional ]
            The default value for the Trait.  Must be list/tuple/set, and
            will be cast to the container type.
        minlen : Int [ default 0 ]
            The minimum length of the input list
        maxlen : Int [ default sys.maxsize ]
            The maximum length of the input list
        Nr  r  r#  rM   rN   r   =  s    "zSet.__init__c                 C   s0   t t|  }|dkrdS d|dd  d S )Nr  zset(){r   r  })r  r   r   )r   Z	list_reprrM   rM   rN   r  a  s    zSet.default_value_repr)rJ   rK   rL   r   r   r  r   rI  r  r  r>   r  r   r   r  r&  rM   rM   r#  rN   r6   4  s   $r6   c                       sR   e Zd ZdZeZefZ fddZdd Z	dd Z
 fdd	Z fd
dZ  ZS )r;   zAn instance of a Python tuple.c                    s6  | dt}t|dkr8|tu r8t|d s8|d }d}|du rj|ddsjtd| jj d	td
d t}|tu rxd}nB|du rd}d|d< n,t	|| j
r|f}ntd| jj d| g | _|D ].}t	|trtdtd
d | }| j| q| jr|du s|tu rd}tt| jf | j|d| dS )aG  Create a tuple from a list, set, or tuple.

        Create a fixed-type tuple with Traits:

        ``t = Tuple(Int(), Str(), CStr())``

        would be length 3, with Int,Str,CStr for each element.

        If only one arg is given and it is not a Trait, it is taken as
        default_value:

        ``t = Tuple((1, 2, 3))``

        Otherwise, ``default_value`` *must* be specified by keyword.

        Parameters
        ----------
        *traits : TraitTypes [ optional ]
            the types for restricting the contents of the Tuple.  If unspecified,
            types are not checked. If specified, then each positional argument
            corresponds to an element of the tuple.  Tuples defined with traits
            are of fixed length.
        default_value : SequenceType [ optional ]
            The default value for the Tuple.  Must be list/tuple/set, and
            will be cast to a tuple. If ``traits`` are specified,
            ``default_value`` must conform to the shape and type they specify.
        **kwargs
            Other kwargs passed to `Container`
        r   r   r   rM   Nr   Fr  r  r   r   r  r  ~Traits should be given as instances, not types (for example, `Int()`, not `Int`) Passing types is deprecated in traitlets 4.1.r  )rK  r>   r   rz   rW   r   r   rJ   ri   rv   r  rh   _traitsrw   r   r  r    r   r  )r   r   r   r   r   r   r#  rM   rN   r   o  s@     

zTuple.__init__c                 C   s(   | j r|t| j kr|S | j | |S )r  )r  r   r   r  rM   rM   rN   r    s    zTuple.item_from_stringc                 C   s   | j s
|S t|t| j krDd| jt|t| j t|f }t|g }t| j |D ]V\}}z|||}W n2 ty } z| ||| W Y d }~qTd }~0 0 |	| qTt
|S )NzTThe '%s' trait of %s instance requires %i elements, but a value of %s was specified.)r  r   r   r   r
   r9   r  r   r  r   r   )r   r   r   rp   r  r   r"  r  rM   rM   rN   r    s     $zTuple.validate_elementsc                    s8   | j D ]}t|tr||d  qtt| || d S rO   )r  rv   r:   r   r  r    r   rk   r   r   r#  rM   rN   r     s    

zTuple.class_initc                    s4   | j D ]}t|tr|| qtt| | d S rO   )r  rv   r:   r   r  r    r   r   r   r#  rM   rN   r     s    

zTuple.instance_init)rJ   rK   rL   r   r   r  rI  r  r   r  r  r   r   r&  rM   rM   r#  rN   r;   i  s   Mr;   c                       s   e Zd ZdZdZdZdddef fdd	ZdddZ fdd	Z	d
d Z
 fddZ fddZdd Zdd Zdd Z  ZS )r"   a  An instance of a Python dict.

    One or more traits can be passed to the constructor
    to validate the keys and/or values of the dict.
    If you need more detailed validation,
    you may use a custom validator method.

    .. versionchanged:: 5.0
        Added key_trait for validating dict keys.

    .. versionchanged:: 5.0
        Deprecated ambiguous ``trait``, ``traits`` args in favor of ``value_trait``, ``per_key_traits``.
    Nc           	         s  | dd}|dur6|dur$td|}tdtdd | dd}|durl|durZtd|}td	tdd |tu r|durt|s|}d}|du r|durt|r|}d}|tu ri }|du rd}n0t|tr|f}nt|tr|f}ntd
| t|r(t|t	r tdtdd | }|| _
n|durBtdt| t|rtt|t	rltdtdd | }|| _n|durtdt| || _t jf t|d| dS )a  Create a dict trait type from a Python dict.

        The default value is created by doing ``dict(default_value)``,
        which creates a copy of the ``default_value``.

        Parameters
        ----------
        value_trait : TraitType [ optional ]
            The specified trait type to check and use to restrict the values of
            the dict. If unspecified, values are not checked.
        per_key_traits : Dictionary of {keys:trait types} [ optional, keyword-only ]
            A Python dictionary containing the types that are valid for
            restricting the values of the dict on a per-key basis.
            Each value in this dict should be a Trait for validating
        key_trait : TraitType [ optional, keyword-only ]
            The type for restricting the keys of the dict. If
            unspecified, the types of the keys are not checked.
        default_value : SequenceType [ optional, keyword-only ]
            The default value for the Dict.  Must be dict, tuple, or None, and
            will be cast to a dict if not None. If any key or value traits are specified,
            the `default_value` must conform to the constraints.

        Examples
        --------
        a dict whose values must be text
        >>> d = Dict(Unicode())

        d2['n'] must be an integer
        d2['s'] must be text
        >>> d2 = Dict(per_key_traits={"n": Integer(), "s": Unicode()})

        d3's keys must be text
        d3's values must be integers
        >>> d3 = Dict(value_trait=Integer(), key_trait=Unicode())

        r   NzFFound a value for both `value_trait` and its deprecated alias `trait`.zIKeyword `trait` is deprecated in traitlets 5.0, use `value_trait` insteadr   r   r   zJFound a value for both `per_key_traits` and its deprecated alias `traits`.zMKeyword `traits` is deprecated in traitlets 5.0, use `per_key_traits` insteadzdefault value of Dict was %sr  z-`value_trait` must be a Trait or None, got %sz+`key_trait` must be a Trait or None, got %sr  )rK  rh   r   ri   r>   rz   rv   r)  r  rw   _value_traitr
   
_key_trait_per_key_traitsr  r   )	r   value_traitZper_key_traits	key_traitr   r   r   r   r   r#  rM   rN   r     s    .






zDict.__init__Valuesc                 C   s.   |d| j t|| t|f  }t|d S )NzN of the '%s' trait of %s instance must be %s, but a value of %s was specified.)r   r   r   r
   r9   )r   r   element	validatorZsiderp   rM   rM   rN   element_errorz  s    zDict.element_errorc                    s*   t  ||}|d u r|S | ||}|S rO   )r  rI   r  r   r#  rM   rN   rI     s
    zDict.validatec           
   
   C   s   | j pi }| j}| j}|s&|s&|s&|S i }|D ]}|| }|rrz|||}W n" typ   | |||d Y n0 |||}	|	rz|	||}W n" ty   | |||	d Y n0 |||< q.| |S )NZKeysr  )r	  r  r  r   r9   r  rW   r  )
r   r   r   Zper_key_overrider  r
  r  rZ   r"  Zactive_value_traitrM   rM   rN   r    s*    

zDict.validate_elementsc                    sl   t | jtr| j|d  t | jtr4| j|d  | jd urZ| j D ]}||d  qHt || d S rO   )rv   r  r:   r   r  r	  rL  r  r  r#  rM   rN   r     s    
zDict.class_initc                    sd   t | jtr| j| t | jtr0| j| | jd urT| j D ]}|| qDt | d S rO   )rv   r  r:   r   r  r	  rL  r  r  r#  rM   rN   r     s    
zDict.instance_initc                 C   sh   t |ts&tdt| dt| z| |gW S  tyb   t|}t |tr\| Y S  Y n0 dS )r  z"from_string expects a string, got z	 of type N)	rv   r{   rh   r  rw   r  r   ru   r)  r  rM   rM   rN   r     s    

zDict.from_stringc                    s   t |dkr"|d dkr" jr"dS t |dkrn|d drn|d drntd j|d t t|d S i } fdd	|D D ]}|	| q|S )
zReturn a dict from a list of config strings.

        This is where we parse CLI configuration.

        Each item should have the form ``"key=value"``.

        item parsing is done in :meth:`.item_from_string`.
        r   r   r   Nr  r  z--{0}={1} for dict-traits is deprecated in traitlets 5.0. You can pass --{0} <key=value> ... multiple times to add items to a dict.c                    s   g | ]}  |qS rM   r  )r   rS   r   rM   rN   r;    r   z)Dict.from_string_list.<locals>.<listcomp>)
r   r   r  r  r   r`   r   r  r   r   )r   r  combinedr@  rM   r   rN   r    s    	(	zDict.from_string_listc                 C   sl   d|vr t d| jjt|f |dd\}}| jrB| j|}| jpJi || j	}|rd||}||iS )a  Cast a single-key dict from a string.

        Evaluated when parsing CLI configuration from a string.

        Dicts expect strings of the form key=value.

        Returns a one-key dictionary,
        which will be merged in :meth:`.from_string_list`.
        r<  z3'%s' options must have the form 'key=value', got %sr   )
r9   r   rJ   r  rd   r  r   r	  rW   r  )r   rS   rZ   r   r
  rM   rM   rN   r    s    
zDict.item_from_string)r  )rJ   rK   rL   r   r  r  r>   r   r  rI   r  r   r   r   r  r  r&  rM   rM   r#  rN   r"     s    


r"   c                   @   s(   e Zd ZdZdZdZdd Zdd ZdS )	r7   zgA trait for an (ip, port) tuple.

    This allows for both IPv4 IP addresses as well as hostnames.
    )z	127.0.0.1r   zan (ip, port) tuplec                 C   s^   t |trNt|dkrNt |d trNt |d trN|d }|dkrN|dkrN|S | || d S )Nr   r   r   i  )rv   r   r   r{   r  r  )r   r   r   portrM   rM   rN   rI     s    
zTCPAddress.validatec                 C   sF   | j r|dkrd S d|vr&td| |dd\}}t|}||fS )Nr   :zRequire `ip:port`, got %rr   )r   rt   rd   r  )r   rS   ipr  rM   rM   rN   r     s    zTCPAddress.from_stringNr  rM   rM   rM   rN   r7     s
   	r7   c                   @   s   e Zd ZdZdZdd ZdS )r   zA casting compiled regular expression trait.

    Accepts both strings and compiled regular expressions. The resulting
    attribute will be a compiled regular expression.za regular expressionc                 C   s0   zt |W S  ty*   | || Y n0 d S rO   )recompiler   r  r   rM   rM   rN   rI   "  s    zCRegExp.validateNrJ   rK   rL   r   r   rI   rM   rM   rM   rN   r     s   r   c                       s   e Zd ZU dZdZejej e	d< dZ
d fdd	ZefddZefd	d
Zdd ZdddZdddZdd Zdd Z  ZS )r@   a  Use a Enum class as model for the data type description.
    Note that if no default-value is provided, the first enum-value is used
    as default-value.

    .. sourcecode:: python

        # -- SINCE: Python 3.4 (or install backport: pip install enum34)
        import enum
        from traitlets import HasTraits, UseEnum

        class Color(enum.Enum):
            red = 1         # -- IMPLICIT: default_value
            blue = 2
            green = 3

        class MyEntity(HasTraits):
            color = UseEnum(Color, default_value=Color.blue)

        entity = MyEntity(color=Color.red)
        entity.color = Color.green    # USE: Enum-value (preferred)
        entity.color = "green"        # USE: name (as string)
        entity.color = "Color.green"  # USE: scoped-name (as string)
        entity.color = 3              # USE: number (as int)
        assert entity.color is Color.green
    Nr   z"Trait type adapter to a Enum classc                    sn   t |tjsJ d| |dd}|d u rB|sBt|j d }t jf d|i| || _	|j
d | _d S )NzREQUIRE: enum.Enum, but was: %rr   Fr   r   r_   )rx   enumr$   rW   rI  __members__rL  r  r   
enum_classrJ   name_prefix)r   r  r   r   r   r#  rM   rN   r   G  s    zUseEnum.__init__c                 C   s:   t |tsJ | jj}| D ]}|j|kr|  S q|S )z0Selects enum-value by using its number-constant.)rv   r  r  r  rL  r   )r   r   rB   enum_membersZ	enum_itemrM   rM   rN   select_by_numberP  s    

zUseEnum.select_by_numberc                 C   s:   t |tsJ || jr*|| jdd}| jj||S )z4Selects enum-value by using its name or scoped-name.r   r   )rv   r{   r  r  replacer  r  rW   )r   r   rB   rM   rM   rN   select_by_nameZ  s    zUseEnum.select_by_namec                 C   s|   t || jr|S t |tr2| |}|turl|S n:t |trT| |}|turl|S n|d u rl| jrfd S | jS | 	|| d S rO   )
rv   r  r  r  r>   r{   r  r   r   r  )r   r   r   Zvalue2rM   rM   rN   rI   b  s    



zUseEnum.validateFc                 C   s4   | j j }|r$ddd |D S tt|S dS )r  r  c                 s   s   | ]}d | V  qdS r  rM   r  rM   rM   rN   r   z  r   z'UseEnum._choices_str.<locals>.<genexpr>N)r  r  r  r  r  rI  r  rM   rM   rN   r  v  s    zUseEnum._choices_strc                 C   s.   | j rd|rdnd nd}d| | | S r  r  r  rM   rM   rN   r  ~  s    zUseEnum._infoc                 C   s   | j ddS r  r  r   rM   rM   rN   r     s    zUseEnum.infoc                 C   s   | j ddS r  r  r   rM   rM   rN   r    s    zUseEnum.info_rst)N)F)F)rJ   rK   rL   r   r   ry   r   r  r$   r   r   r   r>   r  r  rI   r  r  r   r  r&  rM   rM   r#  rN   r@   )  s   
	


r@   c                   @   s   e Zd ZdZdZdd ZdS )r   zxA trait which is callable.

    Notes
    -----
    Classes are callable, as are instances
    with a __call__() method.z
a callablec                 C   s   t |r|S | || d S rO   )rd  r  r   rM   rM   rN   rI     s    zCallable.validateNr  rM   rM   rM   rN   r     s   r   )N)or   r   r  ra   rU   r  r  r  typingry   astr   warningsr   r   Zutils.bunchr   Zutils.descriptionsr   r   r	   r
   Zutils.getargspecr   Zutils.importstringr   Zutils.sentinelr   rI  r   r   	frozensetr  rw   Z
ClassTypes__all__r>   r   ZNoDefaultSpecifiedr   r9   r  Z_name_rerQ   rX   r[   rq   ru   rz   rH   r~   r   r   rE   rC   rD   r   r:   r  r  r2   r3   rF   rG   rI   rB   r%   r5   rA   r!   r+   r,   r   r<   r-   r(   r)   r'   r8   r?   r   r  r.   r   r1   r   r/   r&   r   r   r   r   r   r=   r   r4   r#   r   r   r$   r   r*   r    r0   r6   r;   r"   r7   r   r@   r   rM   rM   rM   rN   <module>   s   )E


QC3  t$.$!)		)     _`X

#

)6 5A5   a