U
    ýÇ-eP.  ã                   @   s   d Z dgZG dd„ deƒZdS )zŽA dict subclass that supports attribute style access.

Authors:

* Fernando Perez (original)
* Brian Granger (refactoring to a dict subclass)
ÚStructc                   @   sˆ   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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S )"r   aY  A dict subclass with attribute style access.

    This dict subclass has a a few extra features:

    * Attribute style access.
    * Protection of class members (like keys, items) when using attribute
      style access.
    * The ability to restrict assignment to only existing keys.
    * Intelligent merging.
    * Overloaded operators.
    Tc                 O   s$   t  | dd¡ tj| f|ž|Ž dS )aÅ  Initialize with a dictionary, another Struct, or data.

        Parameters
        ----------
        *args : dict, Struct
            Initialize with one dict or Struct
        **kw : dict
            Initialize with key, value pairs.

        Examples
        --------
        >>> s = Struct(a=10,b=30)
        >>> s.a
        10
        >>> s.b
        30
        >>> s2 = Struct(s,c=30)
        >>> sorted(s2.keys())
        ['a', 'b', 'c']
        Ú	_allownewTN)ÚobjectÚ__setattr__ÚdictÚ__init__)ÚselfÚargsÚkw© r
   úW/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/IPython/utils/ipstruct.pyr   )   s    zStruct.__init__c                 C   s,   | j s|| krtd| ƒ‚t | ||¡ dS )az  Set an item with check for allownew.

        Examples
        --------
        >>> s = Struct()
        >>> s['a'] = 10
        >>> s.allow_new_attr(False)
        >>> s['a'] = 10
        >>> s['a']
        10
        >>> try:
        ...     s['b'] = 20
        ... except KeyError:
        ...     print('this is not allowed')
        ...
        this is not allowed
        z8can't create new attribute %s when allow_new_attr(False)N)r   ÚKeyErrorr   Ú__setitem__)r   ÚkeyÚvaluer
   r
   r   r   A   s
    ÿzStruct.__setitem__c              
   C   sl   t |tƒr*|| jkstt|ƒr*td| ƒ‚z|  ||¡ W n, tk
rf } zt|ƒ|‚W 5 d}~X Y nX dS )aÃ  Set an attr with protection of class members.

        This calls :meth:`self.__setitem__` but convert :exc:`KeyError` to
        :exc:`AttributeError`.

        Examples
        --------
        >>> s = Struct()
        >>> s.a = 10
        >>> s.a
        10
        >>> try:
        ...     s.get = 10
        ... except AttributeError:
        ...     print("you can't set a class member")
        ...
        you can't set a class member
        z.attr %s is a protected member of class Struct.N)Ú
isinstanceÚstrÚ__dict__Úhasattrr   ÚAttributeErrorr   r   )r   r   r   Úer
   r
   r   r   X   s    
ÿzStruct.__setattr__c              
   C   sB   z| | }W n, t k
r8 } zt|ƒ|‚W 5 d}~X Y nX |S dS )aÌ  Get an attr by calling :meth:`dict.__getitem__`.

        Like :meth:`__setattr__`, this method converts :exc:`KeyError` to
        :exc:`AttributeError`.

        Examples
        --------
        >>> s = Struct(a=10)
        >>> s.a
        10
        >>> type(s.get)
        <...method'>
        >>> try:
        ...     s.b
        ... except AttributeError:
        ...     print("I don't have that key")
        ...
        I don't have that key
        N)r   r   )r   r   Úresultr   r
   r
   r   Ú__getattr__z   s
    zStruct.__getattr__c                 C   s   |   |¡ | S )zás += s2 is a shorthand for s.merge(s2).

        Examples
        --------
        >>> s = Struct(a=10,b=30)
        >>> s2 = Struct(a=20,c=40)
        >>> s += s2
        >>> sorted(s.keys())
        ['a', 'b', 'c']
        )Úmerge)r   Úotherr
   r
   r   Ú__iadd__•   s    
zStruct.__iadd__c                 C   s   |   ¡ }| |¡ |S )zês + s2 -> New Struct made from s.merge(s2).

        Examples
        --------
        >>> s1 = Struct(a=10,b=30)
        >>> s2 = Struct(a=20,c=40)
        >>> s = s1 + s2
        >>> sorted(s.keys())
        ['a', 'b', 'c']
        )Úcopyr   ©r   r   Zsoutr
   r
   r   Ú__add__£   s    
zStruct.__add__c                 C   s   |   ¡ }||8 }|S )zÊs1 - s2 -> remove keys in s2 from s1.

        Examples
        --------
        >>> s1 = Struct(a=10,b=30)
        >>> s2 = Struct(a=40)
        >>> s = s1 - s2
        >>> s
        {'b': 30}
        )r   r   r
   r
   r   Ú__sub__²   s    zStruct.__sub__c                 C   s    |  ¡ D ]}|| kr| |= q| S )zÓInplace remove keys from self that are in other.

        Examples
        --------
        >>> s1 = Struct(a=10,b=30)
        >>> s2 = Struct(a=40)
        >>> s1 -= s2
        >>> s1
        {'b': 30}
        )Úkeys)r   r   Úkr
   r
   r   Ú__isub__Á   s    zStruct.__isub__c                 C   s>   i }|  ¡ D ],\}}t|tƒr&| ¡ }|D ]}|||< q*q|S )z¹Helper function for merge.

        Takes a dictionary whose values are lists and returns a dict with
        the elements of each list as keys and the original keys as values.
        )Úitemsr   r   Úsplit)r   ÚdataZoutdictr    ÚlstÚentryr
   r
   r   Z__dict_invertÑ   s    
zStruct.__dict_invertc                 C   s   | S ©Nr
   ©r   r
   r
   r   r   ß   s    zStruct.dictc                 C   s   t t | ¡ƒS )z®Return a copy as a Struct.

        Examples
        --------
        >>> s = Struct(a=10,b=30)
        >>> s2 = s.copy()
        >>> type(s2) is Struct
        True
        )r   r   r   r(   r
   r
   r   r   â   s    
zStruct.copyc                 C   s   || kS )a  hasattr function available as a method.

        Implemented like has_key.

        Examples
        --------
        >>> s = Struct(a=10)
        >>> s.hasattr('a')
        True
        >>> s.hasattr('b')
        False
        >>> s.hasattr('get')
        False
        r
   )r   r   r
   r
   r   r   î   s    zStruct.hasattrc                 C   s   t  | d|¡ dS )zÇSet whether new attributes can be created in this Struct.

        This can be used to catch typos by verifying that the attribute user
        tries to change already exists in this Struct.
        r   N)r   r   )r   Zallowr
   r
   r   Úallow_new_attrÿ   s    zStruct.allow_new_attrNc                 K   sä   t |f|Ž}dd„ }dd„ }dd„ }dd„ }dd„ }	t  | |¡}
|r¦| ¡ }d|fd|fd	|fd
|fd|	ffD ]&\}}|| ¡ krn|| ||< ||= qn|
 |  |¡¡ |D ]4}|| krÄ|| | |< qª|
| | | || ƒ| |< qªdS )a  Merge two Structs with customizable conflict resolution.

        This is similar to :meth:`update`, but much more flexible. First, a
        dict is made from data+key=value pairs. When merging this dict with
        the Struct S, the optional dictionary 'conflict' is used to decide
        what to do.

        If conflict is not given, the default behavior is to preserve any keys
        with their current value (the opposite of the :meth:`update` method's
        behavior).

        Parameters
        ----------
        __loc_data__ : dict, Struct
            The data to merge into self
        __conflict_solve : dict
            The conflict policy dict.  The keys are binary functions used to
            resolve the conflict and the values are lists of strings naming
            the keys the conflict resolution function applies to.  Instead of
            a list of strings a space separated string can be used, like
            'a b c'.
        **kw : dict
            Additional key, value pairs to merge in

        Notes
        -----
        The `__conflict_solve` dict is a dictionary of binary functions which will be used to
        solve key conflicts.  Here is an example::

            __conflict_solve = dict(
                func1=['a','b','c'],
                func2=['d','e']
            )

        In this case, the function :func:`func1` will be used to resolve
        keys 'a', 'b' and 'c' and the function :func:`func2` will be used for
        keys 'd' and 'e'.  This could also be written as::

            __conflict_solve = dict(func1='a b c',func2='d e')

        These functions will be called for each key they apply to with the
        form::

            func1(self['a'], other['a'])

        The return value is used as the final merged value.

        As a convenience, merge() provides five (the most commonly needed)
        pre-defined policies: preserve, update, add, add_flip and add_s. The
        easiest explanation is their implementation::

            preserve = lambda old,new: old
            update   = lambda old,new: new
            add      = lambda old,new: old + new
            add_flip = lambda old,new: new + old  # note change of order!
            add_s    = lambda old,new: old + ' ' + new  # only for str!

        You can use those four words (as strings) as keys instead
        of defining them as functions, and the merge method will substitute
        the appropriate functions for you.

        For more complicated conflict resolution policies, you still need to
        construct your own functions.

        Examples
        --------
        This show the default policy:

        >>> s = Struct(a=10,b=30)
        >>> s2 = Struct(a=20,c=40)
        >>> s.merge(s2)
        >>> sorted(s.items())
        [('a', 10), ('b', 30), ('c', 40)]

        Now, show how to specify a conflict dict:

        >>> s = Struct(a=10,b=30)
        >>> s2 = Struct(a=20,b=40)
        >>> conflict = {'update':'a','add':'b'}
        >>> s.merge(s2,conflict)
        >>> sorted(s.items())
        [('a', 20), ('b', 70)]
        c                 S   s   | S r'   r
   ©ÚoldÚnewr
   r
   r   Ú<lambda>`  ó    zStruct.merge.<locals>.<lambda>c                 S   s   |S r'   r
   r*   r
   r
   r   r-   a  r.   c                 S   s   | | S r'   r
   r*   r
   r
   r   r-   b  r.   c                 S   s   ||  S r'   r
   r*   r
   r
   r   r-   c  r.   c                 S   s   | d | S )Nú r
   r*   r
   r
   r   r-   d  r.   ÚpreserveÚupdateÚaddÚadd_flipÚadd_sN)r   Úfromkeysr   r   r1   Ú_Struct__dict_invert)r   Z__loc_data__Z_Struct__conflict_solver	   Z	data_dictr0   r1   r2   r3   r4   Zconflict_solveZinv_conflict_solve_userÚnameÚfuncr   r
   r
   r   r     s,    U þzStruct.merge)T)NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r   r   r   r   r!   r6   r   r   r   r)   r   r
   r
   r
   r   r      s    "
N)r<   Ú__all__r   r   r
   r
   r
   r   Ú<module>   s   