3
d4                 @   s  d Z ddlmZ ddlZddlmZmZ ddlmZm	Z	 ddl
mZmZmZ ddl
mZ dd	lmZ dd
lmZmZ ddlmZ ddlmZ ddlmZmZ ddlmZ eefZee	jee fe!e	je!ee fiZ"dZ#dd Z$dd Z%G dd deZ&G dd de&Z'G dd deZ(G dd deZ)G dd deZ*G dd deZ+G d d! d!eZ,G d"d# d#e,Z-G d$d% d%eZ.G d&d' d'eZ/G d(d) d)eZ0d*d+ Z1G d,d- d-eZ2dS ).a  
Defines a standard set of TraitHandler subclasses.

A trait handler mediates the assignment of values to object traits. It
verifies (via its validate() method) that a specified value is consistent
with the object trait, and generates a TraitError exception if it is not
consistent.
    )import_moduleN)FunctionType
MethodType   )DefaultValueValidateTrait)SequenceTypes	TypeTypesclass_of)
RangeTypes)
TraitError)TraitDictEventTraitDictObject)
trait_from)TraitHandler)TraitListEventTraitListObject)
deprecatedzI'{handler}' trait handler has been deprecated. Use {replacement} instead.c             C   s   t d|t| f d S )NzMThe '%s' trait of %s instance is a property that has no 'get' or 'set' method)r   r
   )objectname r   7/tmp/pip-build-7vycvbft/traits/traits/trait_handlers.py_undefined_get6   s    r   c             C   s   t | | d S )N)r   )r   r   valuer   r   r   _undefined_set@   s    r   c               @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )TraitCoerceTypeaB  Ensures that a value assigned to a trait attribute is of a specified
    Python type, or can be coerced to the specified type.

    TraitCoerceType is the underlying handler for the predefined traits and
    factories for Python simple types. The TraitCoerceType class is also an
    example of a parametrized type, because the single TraitCoerceType class
    allows creating instances that check for totally different sets of values.
    For example::

        class Person(HasTraits):
            name = Trait('', TraitCoerceType(''))
            weight = Trait(0.0, TraitCoerceType(float))

    In this example, the **name** attribute must be of type ``str`` (string),
    while the **weight** attribute must be of type ``float``, although both are
    based on instances of the TraitCoerceType class. Note that this example is
    essentially the same as writing::

        class Person(HasTraits):
            name = Trait('')
            weight = Trait(0.0)

    This simpler form is automatically changed by the Trait() function into
    the first form, based on TraitCoerceType instances, when the trait
    attributes are defined.

    For attributes based on TraitCoerceType instances, if a value that is
    assigned is not of the type defined for the trait, a TraitError exception
    is raised. However, in certain cases, if the value can be coerced to the
    required type, then the coerced value is assigned to the attribute. Only
    *widening* coercions are allowed, to avoid any possible loss of precision.
    The following table lists the allowed coercions.

    ============ =================
     Trait Type   Coercible Types
    ============ =================
    complex      float, int
    float        int
    ============ =================

    Parameters
    ----------
    aType : type or object
        Either a Python type or a Python value.  If this is an object, it is
        mapped to its corresponding type. For example, the string 'cat' is
        automatically mapped to ``str``.

    Attributes
    ----------
    aType : type
        A Python type to coerce values to.
   c          	   C   sD   t |tst|}|| _yt| | _W n   tj|f| _Y nX d S )N)
isinstancetypeaTypeCoercableTypesfast_validater   coerce)selfr   r   r   r   __init__z   s    
zTraitCoerceType.__init__c             C   sZ   | j }t|}||d kr|S x(|dd  D ]}||kr,|d |S q,W | j||| d S )Nr      )r    r   error)r"   r   r   r   fvtvZtypeir   r   r   validate   s    zTraitCoerceType.validatec             C   s   dt | jdd  S )Nza value of %sr   )strr   )r"   r   r   r   info   s    zTraitCoerceType.infoc             C   sf   | j tkr.| jd kr(ddlm} | | _| jS |j}|d kr@d}ddlm} |||jpXd| jd dS )Nr   )BooleanEditorT)
TextEditorFr   )auto_set	enter_setevaluate)	r   booleditortraitsui.apir,   r.   r-   r/   r    )r"   traitr,   r.   r-   r   r   r   
get_editor   s    

zTraitCoerceType.get_editorN)__name__
__module____qualname____doc__r#   r(   r+   r5   r   r   r   r   r   D   s
   4	r   c               @   s    e Zd ZdZdd Zdd ZdS )TraitCastTypea5  Ensures that a value assigned to a trait attribute is of a specified
    Python type, or can be cast to the specified type.

    This class is similar to TraitCoerceType, but uses casting rather than
    coercion. Values are cast by calling the type with the value to be assigned
    as an argument. When casting is performed, the result of the cast is the
    value assigned to the trait attribute.

    Any trait that uses a TraitCastType instance in its definition ensures that
    its value is of the type associated with the TraitCastType instance. For
    example::

        class Person(HasTraits):
            name = Trait('', TraitCastType(''))
            weight = Trait(0.0, TraitCastType(float))

    In this example, the **name** trait must be of type ``str`` (string), while
    the **weight** trait must be of type ``float``. Note that this example is
    essentially the same as writing::

        class Person(HasTraits):
            name = CStr
            weight = CFloat

    To understand the difference between TraitCoerceType and TraitCastType (and
    also between Float and CFloat), consider the following example::

        >>> class Person(HasTraits):
        ...     weight = Float
        ...     cweight = CFloat
        ...
        >>> bill = Person()
        >>> bill.weight = 180    # OK, coerced to 180.0
        >>> bill.cweight = 180   # OK, cast to 180.0
        >>> bill.weight = '180'  # Error, invalid coercion
        >>> bill.cweight = '180' # OK, cast to float('180')

    Parameters
    ----------
    aType : type
        Either a Python type or a Python value.  If this is an object, it is
        mapped to its corresponding type. For example, the string 'cat' is
        automatically mapped to ``str``.

    Attributes
    ----------
    aType : type
        A Python type to cast values to.
    c             C   s(   t |tst|}|| _tj|f| _d S )N)r   r   r   r   castr    )r"   r   r   r   r   r#      s    
zTraitCastType.__init__c          
   C   s<   t || jkr|S y
| j|S    | j||| Y nX d S )N)r   r   r%   )r"   r   r   r   r   r   r   r(      s    
zTraitCastType.validateN)r6   r7   r8   r9   r#   r(   r   r   r   r   r:      s   1r:   c               @   sb   e Zd Z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 Zdd Zdd ZdS )TraitInstancea  Ensures that trait attribute values belong to a specified Python type.

    Any trait that uses a TraitInstance handler ensures that its values belong
    to the specified type or class (or one of its subclasses). For example::

        class Employee(HasTraits):
            manager = Trait(None, TraitInstance(Employee, True))

    This example defines a class Employee, which has a **manager** trait
    attribute, which accepts either None or an instance of Employee
    as its value.

    TraitInstance ensures that assigned values are exactly of the type
    specified (i.e., no coercion is performed).

    Parameters
    ----------
    aClass : type, object or str
        A Python type or a string that identifies the type, or an object.
        If this is an object, it is mapped to the class it is an instance of.
        If this is a str, it is either the name  of a class in the module
        identified by the module parameter, or an identifier of the form
        "*module_name*[.*module_name*....].*class_name*".
    allow_none : bool
        Flag indicating whether None is accepted as a valid value.
    module : str
        The name of the module that the class belongs to.  This is ignored if
        the type is provided directly, or the str value is an identifier with
        '.'s in it.

    Attributes
    ----------
    aClass : type or str
        A Python type, or a string which identifies the type.  If this is a
        str, it is either the name of a class in the module identified by the
        module attribute, or an identifier of the form
        "*module_name*[.*module_name*....].*class_name*".  A string value will
        be replaced by the actual type object the first time the trait is used
        to validate an object.
    module : str
        The name of the module that the class belongs to.  This is ignored if
        the type is provided directly, or the str value is an identifier with
        '.'s in it.
    T c             C   s@   || _ || _t|tr|| _nt|ts.|j}|| _| j  d S )N)_allow_nonemoduler   r*   aClassr   	__class__set_fast_validate)r"   r@   
allow_noner?   r   r   r   r#   #  s    

zTraitInstance.__init__c             C   s   d| _ t| dr| j  dS )z Whether or not None is permitted as a valid value.

        Returns
        -------
        bool
            Whether or not None is a valid value.
        Tr    N)r>   hasattrrB   )r"   r   r   r   rC   .  s    
zTraitInstance.allow_nonec             C   sB   t j| jg}| jr t jd | jg}| jtkr4t j|d< t|| _d S )Nr   )r   instancer@   r>   r	   r   tupler    )r"   r    r   r   r   rB   :  s    

zTraitInstance.set_fast_validatec             C   s\   |d kr | j r|S | j||| t| jtr:| j||| t|| jrJ|S | j||| d S )N)r>   r%   r   r@   r*   resolve_class)r"   r   r   r   r   r   r   r(   B  s    zTraitInstance.validatec             C   s2   | j }t|tk	r|j}t|}| jr.|d S |S )Nz or None)r@   r   r*   r6   r
   r>   )r"   r@   resultr   r   r   r+   Q  s    zTraitInstance.infoc             C   sn   | j | j| j}|d kr(| j||| || _| j  |j|}|j}|| k	r^t|dr^|j}|j	| j
 d S )N
item_trait)validate_class
find_classr@   r%   rB   Z
base_traithandlerrD   rI   set_validater    )r"   r   r   r   r@   r4   rL   r   r   r   rG   ]  s    

zTraitInstance.resolve_classc             C   s   | j }|jd}|dkr4|d | }||d d  }ttjj||d }|d kr|dkryt|}t||d }W n tk
r   Y nX |S )N.r   r   )r?   rfindgetattrsysmodulesgetr   	Exception)r"   klassr?   colZtheClassmodr   r   r   rK   r  s    
zTraitInstance.find_classc             C   s   |S )Nr   )r"   r@   r   r   r   rJ     s    zTraitInstance.validate_classc             O   sL   |d }t |tr:| j| j|}|d kr:td|d  ||dd  |S )Nr   zUnable to locate class: r   )r   r*   rJ   rK   r   )r"   argskwr@   r   r   r   create_default_value  s    
z"TraitInstance.create_default_valuec             C   s>   | j d kr8ddlm} ||jp d|jp(d|jp0dd| _ | j S )Nr   )InstanceEditorr=   Zlive)labelviewkind)r2   r3   r[   r\   r]   r^   )r"   r4   r[   r   r   r   r5     s    
zTraitInstance.get_editorN)Tr=   )r6   r7   r8   r9   r#   rC   rB   r(   r+   rG   rK   rJ   rZ   r5   r   r   r   r   r<      s   ,
	r<   c               @   s(   e Zd ZdZdd Zdd Zdd ZdS )	TraitFunctionaX  Ensures that assigned trait attribute values are acceptable to a
    specified validator function.

    TraitFunction is the underlying handler for the predefined trait
    **Function**, and for the use of function references as arguments to the
    Trait() function.

    The signature of the function must be of the form *function*(*object*,
    *name*, *value*). The function must verify that *value* is a legal value
    for the *name* trait attribute of *object*.  If it is, the value returned
    by the function is the actual value assigned to the trait attribute. If it
    is not, the function must raise a TraitError exception.

    Parameters
    ----------
    aFunc : function
        A function to validate trait attribute values.

    Attributes
    ----------
    aFunc : function
        A function to validate trait attribute values.
    c             C   s(   t |tstd|| _tj|f| _d S )NzArgument must be callable.)r   CallableTypesr   aFuncr   functionr    )r"   ra   r   r   r   r#     s    
zTraitFunction.__init__c             C   s6   y| j |||S  tk
r0   | j||| Y nX d S )N)ra   r   r%   )r"   r   r   r   r   r   r   r(     s    zTraitFunction.validatec          	   C   s(   y| j jS    | j jr | j jS dS d S )Nza legal value)ra   r+   r9   )r"   r   r   r   r+     s    zTraitFunction.infoN)r6   r7   r8   r9   r#   r(   r+   r   r   r   r   r_     s   r_   c               @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )	TraitEnuma   Ensures that a value assigned to a trait attribute is a member of a
    specified list of values.

    TraitEnum is the underlying handler for the forms of the Trait() function
    that take a list of possible values

    The list of legal values can be provided as a list or tuple of values.
    That is, ``TraitEnum([1, 2, 3])``, ``TraitEnum((1, 2, 3))`` and
    ``TraitEnum(1, 2, 3)`` are equivalent. For example::

        class Flower(HasTraits):
            color = Trait('white', TraitEnum(['white', 'yellow', 'red']))
            kind  = Trait('annual', TraitEnum('annual', 'perennial'))

    This example defines a Flower class, which has a **color** trait
    attribute, which can have as its value, one of the three strings,
    'white', 'yellow', or 'red', and a **kind** trait attribute, which can
    have as its value, either of the strings 'annual' or 'perennial'. This
    is equivalent to the following class definition::

        class Flower(HasTraits):
            color = Trait(['white', 'yellow', 'red'])
            kind  = Trait('annual', 'perennial')

    The Trait() function automatically maps traits of the form shown in
    this example to the form shown in the preceding example whenever it
    encounters them in a trait definition.

    Parameters
    ----------
    *values
        Either all legal values for the enumeration, or a single list or tuple
        of the legal values.

    Attributes
    ----------
    values : tuple
        Enumeration of all legal values for a trait.
    c             G   s@   t |dkr$t|d tkr$|d }t|| _tj| jf| _d S )Nr   r   )lenr   r   rF   valuesr   enumr    )r"   re   r   r   r   r#     s    
zTraitEnum.__init__c             C   s    || j kr|S | j||| d S )N)re   r%   )r"   r   r   r   r   r   r   r(     s    
zTraitEnum.validatec             C   s   dj dd | jD S )Nz or c             S   s   g | ]}t |qS r   )repr).0xr   r   r   
<listcomp>  s    z"TraitEnum.info.<locals>.<listcomp>)joinre   )r"   r   r   r   r+     s    zTraitEnum.infoc             C   s*   ddl m} || |jpd|j|jp$ddS )Nr   )
EnumEditor   Zradio)re   colsr0   mode)r3   rl   rn   r0   ro   )r"   r4   rl   r   r   r   r5      s    zTraitEnum.get_editorN)r6   r7   r8   r9   r#   r(   r+   r5   r   r   r   r   rc     s
   'rc   c               @   sJ   e Zd ZdZeejd dddd Zdd Zdd	 Z	d
d Z
dd ZdS )TraitPrefixLista  Ensures that a value assigned to a trait attribute is a member of a
    list of specified string values, or is a unique prefix of one of those
    values.

    .. deprecated:: 6.1
        :class:`~.TraitPrefixList` is scheduled for removal in Traits
        7.0. Use the :class:`~.PrefixList` trait type instead.

    TraitPrefixList is a variation on TraitEnum. The values that can be
    assigned to a trait attribute defined using a TraitPrefixList handler is
    the set of all strings supplied to the TraitPrefixList constructor, as well
    as any unique prefix of those strings. That is, if the set of strings
    supplied to the constructor is described by
    [*s*\ :sub:`1`\ , *s*\ :sub:`2`\ , ..., *s*\ :sub:`n`\ ], then the string
    *v* is a valid value for the trait if *v* == *s*\ :sub:`i[:j]` for one and
    only one pair of values (i, j). If *v* is a valid value, then the actual
    value assigned to the trait attribute is the corresponding *s*\ :sub:`i`
    value that *v* matched.

    As with TraitEnum, the list of legal values can be provided as a list
    or tuple of values.  That is, ``TraitPrefixList(['one', 'two', 'three'])``
    and ``TraitPrefixList('one', 'two', 'three')`` are equivalent.

    Example
    -------
    ::

        class Person(HasTraits):
            married = Trait('no', TraitPrefixList('yes', 'no')

    The Person class has a **married** trait that accepts any of the
    strings 'y', 'ye', 'yes', 'n', or 'no' as valid values. However, the actual
    values assigned as the value of the trait attribute are limited to either
    'yes' or 'no'. That is, if the value 'y' is assigned to the **married**
    attribute, the actual value assigned will be 'yes'.

    Note that the algorithm used by TraitPrefixList in determining whether a
    string is a valid value is fairly efficient in terms of both time and
    space, and is not based on a brute force set of comparisons.

    Parameters
    ----------
    *values
        Either all legal string values for the enumeration, or a single list
        or tuple of legal string values.

    Attributes
    ----------
    values : tuple of strings
        Enumeration of all legal values for a trait.
    Z
PrefixList)rL   replacementc             G   sf   t |dkr$t|d tkr$|d }|d d  | _i  | _}x|D ]}|||< qBW tj|| jf| _d S )Nr   r   )	rd   r   r   re   values_r   
prefix_mapr(   r    )r"   re   rr   keyr   r   r   r#   @  s    

zTraitPrefixList.__init__c             C   s   yr|| j krjd }t|}x0| jD ]&}||d | kr |d k	rBd }P |}q W |d kr`| j||| || j |< | j | S    | j||| Y nX d S )N)rr   rd   re   r%   )r"   r   r   r   matchnrt   r   r   r   r(   K  s     


zTraitPrefixList.validatec             C   s   dj dd | jD d S )Nz or c             S   s   g | ]}t |qS r   )rg   )rh   ri   r   r   r   rj   _  s    z(TraitPrefixList.info.<locals>.<listcomp>z (or any unique prefix))rk   re   )r"   r   r   r   r+   ]  s    zTraitPrefixList.infoc             C   s   ddl m} || |jpddS )Nr   )rl   rm   )re   rn   )r3   rl   rn   )r"   r4   rl   r   r   r   r5   c  s    zTraitPrefixList.get_editorc             C   s   | j j }d|kr|d= |S )Nr    )__dict__copy)r"   rH   r   r   r   __getstate__h  s    
zTraitPrefixList.__getstate__N)r6   r7   r8   r9   r   _WARNING_FORMAT_STRformatr#   r(   r+   r5   ry   r   r   r   r   rp     s   3
rp   c               @   sD   e Zd ZdZdZdd Zdd Zdd Zd	d
 Zdd Z	dd Z
dS )TraitMapa   Checks that the value assigned to a trait attribute is a key of a
    specified dictionary, and also assigns the dictionary value corresponding
    to that key to a *shadow* attribute.

    A trait attribute that uses a TraitMap handler is called *mapped* trait
    attribute. In practice, this means that the resulting object actually
    contains two attributes: one whose value is a key of the TraitMap
    dictionary, and the other whose value is the corresponding value of the
    TraitMap dictionary. The name of the shadow attribute is simply the base
    attribute name with an underscore ('_') appended. Mapped trait attributes
    can be used to allow a variety of user-friendly input values to be mapped
    to a set of internal, program-friendly values.

    Example
    -------

    The following example defines a ``Person`` class::

        >>> class Person(HasTraits):
        ...     married = Trait('yes', TraitMap({'yes': 1, 'no': 0 })
        ...
        >>> bob = Person()
        >>> print bob.married
        yes
        >>> print bob.married_
        1

    In this example, the default value of the ``married`` attribute of the
    Person class is 'yes'. Because this attribute is defined using
    TraitPrefixList, instances of Person have another attribute,
    ``married_``, whose default value is 1, the dictionary value corresponding
    to the key 'yes'.

    Parameters
    ----------
    map : dict
        A dictionary whose keys are valid values for the trait attribute,
        and whose corresponding values are the values for the shadow
        trait attribute.

    Attributes
    ----------
    map : dict
        A dictionary whose keys are valid values for the trait attribute,
        and whose corresponding values are the values for the shadow
        trait attribute.
    Tc             C   s   || _ tj |f| _d S )N)mapr   r    )r"   r}   r   r   r   r#     s    zTraitMap.__init__c          
   C   s2   y|| j kr|S W n   Y nX | j||| d S )N)r}   r%   )r"   r   r   r   r   r   r   r(     s    
zTraitMap.validatec             C   s
   | j | S )z# Get the mapped value for a value. )r}   )r"   r   r   r   r   mapped_value  s    zTraitMap.mapped_valuec             C   s4   yt ||d | j| W n   tdY nX d S )N_Z
Unmappable)setattrr~   r   )r"   r   r   r   r   r   r   post_setattr  s    zTraitMap.post_setattrc             C   s"   t dd | jj D }dj|S )Nc             s   s   | ]}t |V  qd S )N)rg   )rh   ri   r   r   r   	<genexpr>  s    z TraitMap.info.<locals>.<genexpr>z or )sortedr}   keysrk   )r"   r   r   r   r   r+     s    zTraitMap.infoc             C   s   ddl m} || |jpddS )Nr   )rl   rm   )re   rn   )r3   rl   rn   )r"   r4   rl   r   r   r   r5     s    zTraitMap.get_editorN)r6   r7   r8   r9   	is_mappedr#   r(   r~   r   r+   r5   r   r   r   r   r|   p  s   /	r|   c                   sB   e Zd ZdZeejd dddd Zdd Z fdd	Z	  Z
S )
TraitPrefixMapaX  A cross between the TraitPrefixList and TraitMap classes.

    .. deprecated:: 6.1
        :class:`~.TraitPrefixMap` is scheduled for removal
        in Traits 7.0. Use the :class:`~.PrefixMap` trait type instead.

    Like TraitMap, TraitPrefixMap is created using a dictionary, but in this
    case, the keys of the dictionary must be strings. Like TraitPrefixList,
    a string *v* is a valid value for the trait attribute if it is a prefix of
    one and only one key *k* in the dictionary. The actual values assigned to
    the trait attribute is *k*, and its corresponding mapped attribute is
    *map*[*k*].

    Example
    -------
    ::

        mapping = {'true': 1, 'yes': 1, 'false': 0, 'no': 0 }
        boolean_map = Trait('true', TraitPrefixMap(mapping))

    This example defines a Boolean trait that accepts any prefix of 'true',
    'yes', 'false', or 'no', and maps them to 1 or 0.

    Parameters
    ----------
    map : dict
        A dictionary whose keys are strings that are valid values for the
        trait attribute, and whose corresponding values are the values for
        the shadow trait attribute.

    Attributes
    ----------
    map : dict
        A dictionary whose keys are strings that are valid values for the
        trait attribute, and whose corresponding values are the values for
        the shadow trait attribute.
    Z	PrefixMap)rL   rq   c             C   s>   || _ i  | _}x|j D ]}|||< qW tj|| jf| _d S )N)r}   _mapr   r   rs   r(   r    )r"   r}   r   rt   r   r   r   r#     s
    
zTraitPrefixMap.__init__c             C   s   yv|| j krnd }t|}x4| jj D ]&}||d | kr$|d k	rFd }P |}q$W |d krd| j||| || j |< | j | S    | j||| Y nX d S )N)r   rd   r}   r   r%   )r"   r   r   r   ru   rv   rt   r   r   r   r(     s     


zTraitPrefixMap.validatec                s   t  j d S )Nz (or any unique prefix))superr+   )r"   )rA   r   r   r+     s    zTraitPrefixMap.info)r6   r7   r8   r9   r   rz   r{   r#   r(   r+   __classcell__r   r   )rA   r   r     s
   %r   c               @   s`   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd ZdS )TraitCompounda   Provides a logical-OR combination of other trait handlers.

    This class provides a means of creating complex trait definitions by
    combining several simpler trait definitions. TraitCompound is the
    underlying handler for the general forms of the Trait() function.

    A value is a valid value for a trait attribute based on a TraitCompound
    instance if the value is valid for at least one of the TraitHandler or
    trait objects supplied to the constructor. In addition, if at least one of
    the TraitHandler or trait objects is mapped (e.g., based on a TraitMap or
    TraitPrefixMap instance), then the TraitCompound is also mapped. In this
    case, any non-mapped traits or trait handlers use identity mapping.

    Parameters
    ----------
    *handlers
        Either all TraitHandlers or trait objects to be combined, or a single
        list or tuple of TraitHandlers or trait objects.

    Attributes
    ----------
    handlers : list or tuple
        A list or tuple of TraitHandler or trait objects to be combined.
    c             G   s6   t |dkr$t|d tkr$|d }|| _| j  d S )Nr   r   )rd   r   r   handlersrM   )r"   r   r   r   r   r#   &  s    zTraitCompound.__init__c       	      C   s|  d| _ d| _d| _g }g }g }g }g }x| jD ]}t|dd }|d k	r||j|j |d tjkrp|j	|d  q|j| n|j|j t|dd }|d k	r|j| |j rd| _ |j| nd| _|jr.d| _q.W || _
|| _| j r|| _nt| dr| `t|dkr:t|dkr(|jtj| f tjt|f| _nt| drJ| `t|dkrh|| _| j| _nt| drx| `d S )NFTr    r   r   r   mapped_handlers)r   	has_itemsZ
reversabler   rP   appendr(   r   complexextend	validatesslow_validatesr   rD   rd   ZslowrF   r    post_setattrs_post_setattrr   )	r"   r   r   r   Zfast_validatesr   rL   r&   r   r   r   r   rM   ,  sT    



zTraitCompound.set_validatec             C   s@   x0| j D ]&}y||||S  tk
r,   Y qX qW | j|||S )N)r   r   slow_validate)r"   r   r   r   r(   r   r   r   r(   k  s    
zTraitCompound.validatec             C   sD   x0| j D ]&}y||||S  tk
r,   Y qX qW | j||| d S )N)r   r   r%   )r"   r   r   r   r(   r   r   r   r   s  s    
zTraitCompound.slow_validatec                s   dj  fdd| jD S )Nz or c                s   g | ]}|j  qS r   )	full_info)rh   ri   )r   r   r   r   r   rj   }  s    z+TraitCompound.full_info.<locals>.<listcomp>)rk   r   )r"   r   r   r   r   )r   r   r   r   r   {  s    zTraitCompound.full_infoc             C   s   dj dd | jD S )Nz or c             S   s   g | ]}|j  qS r   )r+   )rh   ri   r   r   r   rj     s    z&TraitCompound.info.<locals>.<listcomp>)rk   r   )r"   r   r   r   r+     s    zTraitCompound.infoc          
   C   s,   x&| j D ]}y
|j|S    Y qX qW |S )N)r   r~   )r"   r   rL   r   r   r   r~     s    

zTraitCompound.mapped_valuec             C   sJ   x4| j D ]*}y|||| d S  tk
r0   Y qX qW t||d | d S )Nr   )r   r   r   )r"   r   r   r   r   r   r   r   r     s    
zTraitCompound._post_setattrc       	         sr   ddl m}m}  fdd| jD }| }d}g }x4|D ],}t||jrZ|d7 }|dkrZq8|j| q8W ||dS )Nr   )r-   CompoundEditorc                s   g | ]}|j  qS r   )r5   )rh   ri   )r4   r   r   rj     s    z,TraitCompound.get_editor.<locals>.<listcomp>r   )editors)r3   r-   r   r   r   rA   r   )	r"   r4   r-   r   Zthe_editorsZtext_editorcountr   r2   r   )r4   r   r5     s    
zTraitCompound.get_editorc             C   s   t  S )N)items_event)r"   r   r   r   r     s    zTraitCompound.items_eventN)r6   r7   r8   r9   r#   rM   r(   r   r   r+   r~   r   r5   r   r   r   r   r   r     s   ?	r   c               @   sJ   e Zd ZdZeejd dddd Zdd Zdd	 Z	d
d Z
dd ZdS )
TraitTupleae   Ensures that values assigned to a trait attribute are tuples of a
    specified length, with elements that are of specified types.

    TraitTuple is the underlying handler for the predefined trait **Tuple**,
    and the trait factory Tuple().

    Example
    -------

    The following example defines a ``Card`` class::

        rank = Range(1, 13)
        suit = Trait('Hearts', 'Diamonds', 'Spades', 'Clubs')
        class Card(HasTraits):
            value = Trait(TraitTuple(rank, suit))

    The Card class has a **value** trait attribute,
    which must be a tuple of two elments. The first element must be an integer
    in the range from 1 to 13, and the second element must be one of the four
    strings, 'Hearts', 'Diamonds', 'Spades', or 'Clubs'.

    Parameters
    ----------
    *args
        The traits, each *trait*\ :sub:`i` specifies the type that
        the *i*\ th element of a tuple must be.  Each *trait*\ :sub:`i`
        must be either a trait, or a value that can be
        converted to a trait using the trait_from() function. The resulting
        trait handler accepts values that are tuples of the same length as
        *args*, and whose *i*\ th element is of the type specified by
        *trait*\ :sub:`i`.

    Parameters
    ----------
    types : tuple of CTrait instances
        The traits to use for each item in a validated tuple.
    Tuple)rL   rq   c             G   s&   t dd |D | _tj | jf| _d S )Nc             S   s   g | ]}t |qS r   )r   )rh   argr   r   r   rj     s    z'TraitTuple.__init__.<locals>.<listcomp>)rF   typesr   r    )r"   rX   r   r   r   r#     s    zTraitTuple.__init__c             C   s   y`t |tr^| j}t|t|kr^g }x.t|D ]"\}}|j|jj||||  q0W t|S W n   Y nX | j||| d S )N)	r   rF   r   rd   	enumerater   rL   r(   r%   )r"   r   r   r   r   re   ir   r   r   r   r(     s    
zTraitTuple.validatec                s$   ddj  fddjD  S )Nza tuple of the form: (%s)z, c                s   g | ]}j | qS r   )_trait_info)rh   r   )r   r   r"   r   r   r   rj     s   z(TraitTuple.full_info.<locals>.<listcomp>)rk   r   )r"   r   r   r   r   )r   r   r"   r   r   r     s    zTraitTuple.full_infoc             C   s    |j }|d krdS |j|||S )Nz	any value)rL   r   )r"   r   r   r   r   rL   r   r   r   r     s    zTraitTuple._trait_infoc             C   s(   ddl m} || j|jpg |jp"ddS )Nr   )TupleEditorr   )r   labelsrn   )r3   r   r   r   rn   )r"   r4   r   r   r   r   r5     s    zTraitTuple.get_editorN)r6   r7   r8   r9   r   rz   r{   r#   r(   r   r   r5   r   r   r   r   r     s   %
r   c               @   sl   e Zd ZdZdZejZdZe	e
jd ddddejdfddZd	d
 Zdd Zdd Zdd Zdd ZdS )	TraitLista   Ensures that a value assigned to a trait attribute is a list containing
    elements of a specified type, and that the length of the list is also
    within a specified range.

    TraitList also makes sure that any changes made to the list after it is
    assigned to the trait attribute do not violate the list's type and length
    constraints. TraitList is the underlying handler for the predefined
    list-based traits.

    Example
    -------
    ::

        class Card(HasTraits):
            pass

        class Hand(HasTraits):
            cards = Trait([], TraitList(Trait(Card), maxlen=52))

    This example defines a Hand class, which has a **cards** trait attribute,
    which is a list of Card objects and can have from 0 to 52 items in the
    list.

    Parameters
    ----------
    trait : Trait
        The type of items the list can contain. If this is None or omitted,
        then no type checking is performed on any items in the list;
        otherwise, this must be either a trait, or a value that can be
        converted to a trait using the trait_from() function.
    minlen : int
        The minimum length of the list.
    maxlen : int
        The maximum length of the list.
    has_items : bool
        Flag indicating whether the list contains elements.

    Attributes
    ----------
    item_trait : CTrait or None
        The type of items the list can contain.  If None, no type checking is
        performed on the items of the list.
    minlen : int
        The minimum length of the list.
    maxlen : int
        The maximum length of the list.
    has_items : bool
        Flag indicating whether the list contains elements.
    NList)rL   rq   r   Tc             C   s,   t || _td|| _t||| _|| _d S )Nr   )r   rI   maxminlenmaxlenr   )r"   r4   r   r   r   r   r   r   r#   5  s    
zTraitList.__init__c             C   s   t | j| j| j| jS )N)r   rI   r   r   r   )r"   r   r   r   clone?  s    zTraitList.clonec             C   sJ   t |tr8| jt|  ko$| jkn  r8t| |||S | j||| d S )N)r   listr   rd   r   r   r%   )r"   r   r   r   r   r   r   r(   D  s    
 zTraitList.validatec             C   s   | j dkr(| jtjkrd}qPd| j }n(| jtjkr@d| j  }nd| j | jf }| jj}|d krfd}nd|j||| }d||f S )	Nr   itemszat most %d itemszat least %d itemszfrom %s to %s itemsr=   z which are %sza list of %s%s)r   r   rQ   maxsizerI   rL   r   )r"   r   r   r   sizerL   r+   r   r   r   r   L  s    
zTraitList.full_infoc             C   s   ddl m} ||| S )Nr   )list_editor)Ztraits.editor_factoriesr   )r"   r4   r   r   r   r   r5   _  s    zTraitList.get_editorc             C   s   t  S )N)r   )r"   r   r   r   r   d  s    zTraitList.items_event)r6   r7   r8   r9   
info_traitr   trait_list_objectdefault_value_type_items_eventr   rz   r{   rQ   r   r#   r   r(   r   r5   r   r   r   r   r   r     s   1
r   c              C   s.   ddl m}  tjd kr(| tddj t_tjS )Nr   )EventF)is_base)trait_typesr   r   r   r   	as_ctrait)r   r   r   r   r   h  s
    
r   c               @   sb   e Zd ZdZdZejZdZe	e
jd dddddZdd	 Zd
d Zdd Zdd Zdd ZdS )	TraitDicta   Ensures that values assigned to a trait attribute are dictionaries
    whose keys and values are of specified types.

    TraitDict also makes sure that any changes to keys or values made that are
    made after the dictionary is assigned to the trait attribute satisfy the
    type constraints. TraitDict is the underlying handler for the
    dictionary-based predefined traits, and the Dict() trait factory.

    Example
    -------
    ::

        class WorkoutClass(HasTraits):
            member_weights = Trait({}, TraitDict(str, float))


    This example defines a WorkoutClass class containing a *member_weights*
    trait attribute whose value must be a dictionary containing keys that
    are strings (i.e., the members' names) and whose associated values must
    be floats (i.e., their most recently recorded weight).

    Parameters
    ----------
    key_trait : trait
        The type for the dictionary keys.  If this is None or omitted, the
        keys in the dictionary can be of any type. Otherwise, this
        must be either a trait, or a value that can be converted to a trait
        using the trait_from() function. In this case, all dictionary keys are
        checked to ensure that they are of the type specified.
    value_trait : trait
        The type for the dictionary values.  If this is None or omitted, the
        values in the dictionary can be of any type. Otherwise, this must be
        either a trait, or a value that can be converted to a trait using the
        trait_from() function.  In this case, all dictionary values are
        checked to ensure that they are of the type specified.
    has_items : bool
        Flag indicating whether the dictionary contains entries.

    Attributes
    ----------
    key_trait : CTrait or TraitHandler or None
        The type for the dictionary keys.  If this is None then the keys are
        not validated.
    value_trait : CTrait or TraitHandler or None
        The type for the dictionary values.  If this is None then the values
        are not validated.
    value_handler : BaseTraitHandler or None
        The trait handler for the dictionary values.
    has_items : bool
        Flag indicating whether the dictionary contains entries.
    NDict)rL   rq   Tc             C   s@   t || _t || _|| _| jj}|jr6|j }d|_|| _d S )NF)r   	key_traitvalue_traitr   rL   r   value_handler)r"   r   r   r   rL   r   r   r   r#     s    

zTraitDict.__init__c             C   s   t | j| j| jS )N)r   r   r   r   )r"   r   r   r   r     s    zTraitDict.clonec             C   s*   t |trt| |||S | j||| d S )N)r   dictr   r%   )r"   r   r   r   r   r   r   r(     s    
zTraitDict.validatec             C   sh   d}| j j}|d k	r&d|j||| }| j}|d k	r`|dkrBd}n|d7 }|d|j||| 7 }d| S )Nr=   z with keys which are %sz withz andz values which are %sza dictionary%s)r   rL   r   r   )r"   r   r   r   extrarL   r   r   r   r     s    zTraitDict.full_infoc             C   s(   | j d kr"ddlm} |td| _ | j S )Nr   )r-   )r0   )r2   r3   r-   eval)r"   r4   r-   r   r   r   r5     s    
zTraitDict.get_editorc             C   s.   ddl m} tjd kr(|tddj t_tjS )Nr   )r   F)r   )r   r   r   r   r   r   )r"   r   r   r   r   r     s
    
zTraitDict.items_event)NNT)r6   r7   r8   r9   r   r   r   r   r   r   rz   r{   r#   r   r(   r   r5   r   r   r   r   r   r   s  s   3

r   )3r9   	importlibr   rQ   r   r   r   	constantsr   r   Z
trait_baser   r	   r
   r   Ztrait_errorsr   Ztrait_dict_objectr   r   Ztrait_convertersr   Ztrait_handlerr   r   r   r   Zutil.deprecatedr   r`   floatr!   intr   r   rz   r   r   r   r:   r<   r_   rc   rp   r|   r   r   r   r   r   r   r   r   r   r   <module>   sB   
lE '.BeVF Vj