3
dE                 @   s~   d dl Z d dlZd dlmZ d dlmZ d dlmZmZ d dl	m
Z
 G dd deZejG dd	 d	eZG d
d deZdS )    N)ref)IObservable)	Undefined_validate_everything)
TraitErrorc               @   s*   e Zd ZdZddddddZdd ZdS )TraitDictEventa2   An object reporting in-place changes to a traits dict.

    Parameters
    ----------
    removed : dict, optional
        Old keys and values that were just removed.
    added : dict, optional
        New keys and values that were just added.
    changed : dict, optional
        Updated keys and their previous values.

    Attributes
    ----------
    removed : dict
        Old keys and values that were just removed.
    added : dict
        New keys and values that were just added.
    changed : dict
        Updated keys and their previous values.
    N)removedaddedchangedc            C   s:   |d kri }|| _ |d kri }|| _|d kr0i }|| _d S )N)r   r	   r
   )selfr   r	   r
    r   :/tmp/pip-build-7vycvbft/traits/traits/trait_dict_object.py__init__*   s    zTraitDictEvent.__init__c             C   s&   | j j d| jd| jd| jdS )Nz	(removed=z, added=z
, changed=))	__class____name__r   r	   r
   )r   r   r   r   __repr__7   s    zTraitDictEvent.__repr__)r   
__module____qualname____doc__r   r   r   r   r   r   r      s   r   c                   s   e Zd ZdZ fddZd$dddd fddZdd	 Z fd
dZ fddZe	j
d%krf fddZ fddZ fddZd& fdd	Zef fdd	Z fddZdd Zdd Zd d! Zd"d# Z  ZS )'	TraitDictaX   A subclass of dict that validates keys and values and notifies
    listeners of any change.

    Parameters
    ----------
    value : dict or iterable, optional
        The initial dict or an iterable containing key-value pairs.
    key_validator : callable, optional
        Called to validate a key in the dict.
        The callable must accept a single key and
        return a validated key or raise a TraitError
        If not provided, all keys are considered valid.
    value_validator : callable, optional
        Called to validate a value in the dict.
        The callable must accept a single value and
        return a validated value or raise a TraitError
        If not provided, all values are considered valid.
    notifiers : list, optional
        A list of callables with the signature::

            notifier(trait_dict, removed, added, changed)

        Where:
        'removed' is a dict of key-values that are no longer in the dictionary.
        'added' is a dict of new key-values that have been added.
        'changed' is a dict with old values previously associated with the key.

    Attributes
    ----------
    key_validator : callable
        Called to validate a key in the dict.
        The callable must accept a single key and
        return a validated key or raise a TraitError
    value_validator : callable
        Called to validate a value in the dict.
        The callable must accept a single value and
        return a validated value or raise a TraitError
    notifiers : list
        A list of callables with the signature::

            notifier(trait_dict, removed, added, changed)

        Where:
        'removed' is a dict of key-values that are no longer in the dictionary.
        'added' is a dict of new key-values that have been added.
        'changed' is a dict with old values previously associated with the key.
    c                s"   t  j| }t|_t|_g |_|S )N)super__new__r   key_validatorvalue_validator	notifiers)clsargskwargsr   )r   r   r   r   r   s
    zTraitDict.__new__N)r   r   r   c               sr   |d k	r| _ |d k	r| _|d kr(g }| _|d kr:i }t|drL|j n|} fdd|D }t j| d S )Nkeysc                s"   i | ]\}} j | j|qS r   )r   r   ).0keyvalue)r   r   r   
<dictcomp>   s   z&TraitDict.__init__.<locals>.<dictcomp>)r   r   r   hasattritemsr   r   )r   r"   r   r   r   r%   )r   )r   r   r   y   s    
zTraitDict.__init__c             C   s"   x| j D ]}|| ||| qW dS )a   Call all notifiers.

        This simply calls all notifiers provided by the class, if any.
        The notifiers are expected to have the signature::

            notifier(trait_dict, removed, added, changed)

        Any return values are ignored.
        N)r   )r   r   r	   r
   notifierr   r   r   notify   s    zTraitDict.notifyc                s`   i }| j |}| j|}|| kr2|| | i}i }ni }||i}t j|| | j|||d dS )z Set a value for the key, implements self[key] = value.

        Parameters
        ----------
        key : A hashable object.
            The key for the value.
        value : any
            The value to set for the corresponding key.
        )r   r	   r
   N)r   r   r   __setitem__r'   )r   r!   r"   r   validated_keyvalidated_valuer
   r	   )r   r   r   r(      s    

zTraitDict.__setitem__c                s8   || kr|| | ini }t  j| | j|i i d dS )z Delete the item from the dict indicated by the key.

        Parameters
        ----------
        key : A hashable object.
            The key to be deleted.

        Raises
        ------
        KeyError
            If the key is not found.
        )r   r	   r
   N)r   __delitem__r'   )r   r!   r   )r   r   r   r+      s    zTraitDict.__delitem__   	   c                s   i }i }i }t |dr|j n|}xJ|D ]B\}}| j|}| j|}	|| krZ| | ||< n|	||< |	||< q(W t j|}
|s|r| ji ||d |
S )z Update self with the contents of other.

            Parameters
            ----------
            other : mapping or iterable of (key, value) pairs
                Values to be added to this dictionary.
            r   )r   r	   r
   )r$   r%   r   r   r   __ior__r'   )r   othervalidated_dictr	   r
   r%   r!   r"   r)   r*   retval)r   r   r   r.      s    

zTraitDict.__ior__c                s2   | i k}| j  }t j  |s.| j|i i d dS )z! Remove all items from the dict. )r   r	   r
   N)copyr   clearr'   )r   Z	was_emptyr   )r   r   r   r3      s
    
zTraitDict.clearc       
         s   i }i }i }t |dr|j n|}xJ|D ]B\}}| j|}| j|}	|| krZ| | ||< n|	||< |	||< q(W t j| |s|r| ji ||d dS )z Update the values in the dict by the new dict or an iterable of
        key-value pairs.

        Parameters
        ----------
        other : dict or iterable
            The dict from which values will be updated into this dict.
        r   )r   r	   r
   N)r$   r%   r   r   r   updater'   )
r   r/   r0   r	   r
   r%   r!   r"   r)   r*   )r   r   r   r4      s    


zTraitDict.updatec                sl   || kr| | S | j |}| j|}|| kr>|| | i}i }ni }||i}t j|| | ji ||d |S )z Returns the value if key is present in the dict, else creates the
        key-value pair and returns the value.

        Parameters
        ----------
        key : A hashable object.
            Key to the item.
        )r   r	   r
   )r   r   r   r(   r'   )r   r!   r"   r)   r*   r
   r	   )r   r   r   
setdefault  s    


zTraitDict.setdefaultc                sP   |t kp|| k}|t kr&t j|}nt j||}|rL| j||ii i d |S )aZ   Remove specified key and return the corresponding
        value. If key is not found, the default value is returned
        if given, otherwise KeyError is raised.

        Parameters
        ----------
        key : A hashable object.
            Key to the dict item.

        value : any
            Value to return if key is absent.
        )r   r	   r
   )r   r   popr'   )r   r!   r"   Zshould_notifyr   )r   r   r   r6   0  s    zTraitDict.popc                s$   t  j }| jt|gi i d |S )a   Remove and return some (key, value) pair as a tuple. Raise KeyError
        if dict is empty.

        Returns
        -------
        key_value : tuple
            Some 2-tuple from the dict.

        Raises
        ------
        KeyError
            If the dict is empty
        )r   r	   r
   )r   popitemr'   dict)r   item)r   r   r   r7   L  s    
zTraitDict.popitemc             C   s   | j j }|d= |S )zw Get the state of the object for serialization.

        Notifiers are transient and should not be serialized.
        r   )__dict__r2   )r   resultr   r   r   __getstate__a  s    
zTraitDict.__getstate__c             C   s   g |d< | j j| dS )z Restore the state of the object after serialization.

        Notifiers are transient and are restored to the empty list.
        r   N)r:   r4   )r   stater   r   r   __setstate__l  s    zTraitDict.__setstate__c                s>   t t fdd| j D tj| j tj| j g d}|S )zb Perform a deepcopy operation.

        Notifiers are transient and should not be copied.
        c             3   s   | ]}t j| V  qd S )N)r2   deepcopy)r    x)memor   r   	<genexpr>|  s    z)TraitDict.__deepcopy__.<locals>.<genexpr>)r   r   r   )r   r8   r%   r2   r?   r   r   )r   rA   r;   r   )rA   r   __deepcopy__u  s    zTraitDict.__deepcopy__c             C   s   | j S )a   Return a list of callables where each callable is a notifier.
        The list is expected to be mutated for contributing or removing
        notifiers from the object.

        Parameters
        ----------
        force_create: boolean
            Not used here.
        )r   )r   Zforce_creater   r   r   
_notifiers  s    
zTraitDict._notifiers)N)r,   r-   )N)r   r   r   r   r   r   r'   r(   r+   sysversion_infor.   r3   r4   r5   r   r6   r7   r<   r>   rC   rD   __classcell__r   r   )r   r   r   @   s$   0
 		r   c                   sT   e Zd ZdZ fddZdd Zdd Zdd	 Z fd
dZdd Z	dd Z
  ZS )TraitDictObjecta[   A subclass of TraitDict that fires trait events when mutated.
    This is for backward compatibility with Traits 6.0 and lower.

    This is used by the Dict trait type, and all values set into a Dict
    trait will be copied into a new TraitDictObject instance.

    Mutation of the TraitDictObject will fire a "name_items" event with
    appropriate added, changed and removed values.

    Parameters
    ----------
    trait : CTrait instance
        The CTrait instance associated with the attribute that this dict
        has been set to.
    object : HasTraits
        The object this dict belongs to. Can also be None in cases where the
        dict has been disconnected from its HasTraits parent.
    name : str
        The name of the attribute on the object.
    value : dict
        The dict of values to initialize the TraitDictObject with.

    Attributes
    ----------
    trait : CTrait instance
        The CTrait instance associated with the attribute that this dict
        has been set to.
    object : callable
        A callable that when called with no arguments returns the HasTraits
        object that this dict belongs to, or None if there is no such object.
    name : str
        The name of the attribute on the object.
    name_items : str
        The name of the items event trait that the trait dict will fire when
        mutated.
    c                s\   || _ |d krdd nt|| _|| _d | _|jr<|d | _t j|| j| j	| j
gd d S )Nc               S   s   d S )Nr   r   r   r   r   <lambda>  s    z*TraitDictObject.__init__.<locals>.<lambda>Z_items)r   r   r   )traitr   objectname
name_itemsZ	has_itemsr   r   _key_validator_value_validatorr&   )r   rJ   rK   rL   r"   )r   r   r   r     s    
zTraitDictObject.__init__c             C   s   t | dd}t | ddd  }|dks.|dkr2|S |jj}|dkrF|S y||| j|S  tk
r } z|jd |W Y dd}~X nX dS )aa   Key validator based on the Dict's key_trait.

        Parameters
        ----------
        key : A hashable object.
            The key to validate.

        Returns
        -------
        validated_key : A hashable object.
            The validated key.

        Raises
        ------
        TraitError
            If the validation fails.
        rJ   NrK   c               S   s   d S )Nr   r   r   r   r   rI     s    z0TraitDictObject._key_validator.<locals>.<lambda>zEach key of the)getattrZ	key_traitvalidaterL   r   
set_prefix)r   r!   rJ   rK   rQ   excepr   r   r   rN     s    
zTraitDictObject._key_validatorc             C   s   t | dd}t | ddd  }|dks.|dkr2|S |jj}|dkrF|S y||| j|S  tk
r } z|jd |W Y dd}~X nX dS )aO   Value validator based on the Dict's value_trait.

        Parameters
        ----------
        value : any
            The value to validate.

        Returns
        -------
        validated_value : any
            The validated value.

        Raises
        ------
        TraitError
            If the validation fails.
        rJ   NrK   c               S   s   d S )Nr   r   r   r   r   rI     s    z2TraitDictObject._value_validator.<locals>.<lambda>zEach value of the)rP   Zvalue_traitrQ   rL   r   rR   )r   r"   rJ   rK   rQ   rS   r   r   r   rO     s    
z TraitDictObject._value_validatorc             C   sb   | j dkrdS | j }|dkr"dS t|| j| k	r6dS t|||d}| jj }|j| j || dS )aO   Fire the TraitDictEvent with the provided parameters.

        Parameters
        ----------
        trait_dict : dict
            The complete dictionary.
        removed : dict
            Dict of removed items.
        added : dict
            Dict of added items.
        changed : dict
            Dict of changed items.
        N)r   r	   r
   )rM   rK   rP   rL   r   rJ   items_eventZtrait_items_event)r   Z
trait_dictr   r	   r
   rK   eventrT   r   r   r   r&     s    

zTraitDictObject.notifierc                s   t  j }|d= |d= |S )zl Get the state of the object for serialization.

        Object and trait should not be serialized.
        rK   rJ   )r   r<   )r   r;   )r   r   r   r<   1  s    
zTraitDictObject.__getstate__c             C   s<   |j dd | jg|d< dd |d< d|d< | jj| dS )	z> Restore the state of the object after serialization.
        rL    r   c               S   s   d S )Nr   r   r   r   r   rI   B  s    z.TraitDictObject.__setstate__.<locals>.<lambda>rK   NrJ   )r5   r&   r:   r4   )r   r=   r   r   r   r>   <  s
    zTraitDictObject.__setstate__c                s,   t | jd| jt fdd| j D }|S )z_ Perform a deepcopy operation..

        Object is a weakref and should not be copied.
        Nc             3   s   | ]}t j| V  qd S )N)r2   r?   )r    r@   )rA   r   r   rB   O  s    z/TraitDictObject.__deepcopy__.<locals>.<genexpr>)rH   rJ   rL   r8   r%   )r   rA   r;   r   )rA   r   rC   F  s    zTraitDictObject.__deepcopy__)r   r   r   r   r   rN   rO   r&   r<   r>   rC   rG   r   r   )r   r   rH     s   $%%#
rH   )r2   rE   weakrefr   Ztraits.observation.i_observabler   Ztraits.trait_baser   r   Ztraits.trait_errorsr   rK   r   registerr8   r   rH   r   r   r   r   <module>   s   ,  S