Format: application/x-python-code
⬇ Download File (10.7 KB)
   1  o
   2  
   3  ��hP.�@sdZdgZGdd�de�ZdS)z�A dict subclass that supports attribute style access.
   4  
   5  Authors:
   6  
   7  * Fernando Perez (original)
   8  * Brian Granger (refactoring to a dict subclass)
   9  �Structc@s�eZdZdZdZdd�Zdd�Zdd�Zd	d
  10  �Zdd�Z	d
  11  d�Z
  12  dd�Zdd�Zdd�Z
  13  dd�Zdd�Zdd�Zd dd�Zd!dd�ZdS)"raYA dict subclass with attribute style access.
  14  
  15      This dict subclass has a a few extra features:
  16  
  17      * Attribute style access.
  18      * Protection of class members (like keys, items) when using attribute
  19        style access.
  20      * The ability to restrict assignment to only existing keys.
  21      * Intelligent merging.
  22      * Overloaded operators.
  23      TcOs*t�|dd�tj|g|�Ri|��dS)a�Initialize with a dictionary, another Struct, or data.
  24  
  25          Parameters
  26          ----------
  27          *args : dict, Struct
  28              Initialize with one dict or Struct
  29          **kw : dict
  30              Initialize with key, value pairs.
  31  
  32          Examples
  33          --------
  34          >>> s = Struct(a=10,b=30)
  35          >>> s.a
  36          10
  37          >>> s.b
  38          30
  39          >>> s2 = Struct(s,c=30)
  40          >>> sorted(s2.keys())
  41          ['a', 'b', 'c']
  42          �	_allownewTN)�object�__setattr__�dict�__init__)�self�args�kw�r
  43  �Lc:\Users\shubh\Videos\agent\nova\Lib\site-packages\IPython/utils/ipstruct.pyr)szStruct.__init__cCs,|js
  44  ||vr
  45  td|��t�|||�dS)azSet an item with check for allownew.
  46  
  47          Examples
  48          --------
  49          >>> s = Struct()
  50          >>> s['a'] = 10
  51          >>> s.allow_new_attr(False)
  52          >>> s['a'] = 10
  53          >>> s['a']
  54          10
  55          >>> try:
  56          ...     s['b'] = 20
  57          ... except KeyError:
  58          ...     print('this is not allowed')
  59          ...
  60          this is not allowed
  61          z8can't create new attribute %s when allow_new_attr(False)N)r�KeyErrorr�__setitem__)r�key�valuer
  62  r
  63  rr
  64  As
  65  �zStruct.__setitem__c
  66  Cs`t|t�r||jvstt|�rtd|��z	|�||�WdSty/}zt|�|�d}~ww)a�Set an attr with protection of class members.
  67  
  68          This calls :meth:`self.__setitem__` but convert :exc:`KeyError` to
  69          :exc:`AttributeError`.
  70  
  71          Examples
  72          --------
  73          >>> s = Struct()
  74          >>> s.a = 10
  75          >>> s.a
  76          10
  77          >>> try:
  78          ...     s.get = 10
  79          ... except AttributeError:
  80          ...     print("you can't set a class member")
  81          ...
  82          you can't set a class member
  83          z.attr %s is a protected member of class Struct.N)�
  84  isinstance�str�__dict__�hasattrr�AttributeErrorr
  85  r)rrr�er
  86  r
  87  rrXs
  88  �
  89  ��zStruct.__setattr__c
  90  Cs2z||}W|Sty}zt|�|�d}~ww)a�Get an attr by calling :meth:`dict.__getitem__`.
  91  
  92          Like :meth:`__setattr__`, this method converts :exc:`KeyError` to
  93          :exc:`AttributeError`.
  94  
  95          Examples
  96          --------
  97          >>> s = Struct(a=10)
  98          >>> s.a
  99          10
 100          >>> type(s.get)
 101          <...method'>
 102          >>> try:
 103          ...     s.b
 104          ... except AttributeError:
 105          ...     print("I don't have that key")
 106          ...
 107          I don't have that key
 108          N)rr)rr�resultrr
 109  r
 110  r�__getattr__zs
 111  �
 112  ��zStruct.__getattr__cCs|�|�|S)z�s += s2 is a shorthand for s.merge(s2).
 113  
 114          Examples
 115          --------
 116          >>> s = Struct(a=10,b=30)
 117          >>> s2 = Struct(a=20,c=40)
 118          >>> s += s2
 119          >>> sorted(s.keys())
 120          ['a', 'b', 'c']
 121          )�merge)r�otherr
 122  r
 123  r�__iadd__�s
 124  zStruct.__iadd__cCs|��}|�|�|S)z�s + s2 -> New Struct made from s.merge(s2).
 125  
 126          Examples
 127          --------
 128          >>> s1 = Struct(a=10,b=30)
 129          >>> s2 = Struct(a=20,c=40)
 130          >>> s = s1 + s2
 131          >>> sorted(s.keys())
 132          ['a', 'b', 'c']
 133          )�copyr�rrZsoutr
 134  r
 135  r�__add__�s
 136  zStruct.__add__cCs|��}||8}|S)z�s1 - s2 -> remove keys in s2 from s1.
 137  
 138          Examples
 139          --------
 140          >>> s1 = Struct(a=10,b=30)
 141          >>> s2 = Struct(a=40)
 142          >>> s = s1 - s2
 143          >>> s
 144          {'b': 30}
 145          )rrr
 146  r
 147  r�__sub__�szStruct.__sub__cCs |��D]	}||vr
 148  ||=q|S)z�Inplace remove keys from self that are in other.
 149  
 150          Examples
 151          --------
 152          >>> s1 = Struct(a=10,b=30)
 153          >>> s2 = Struct(a=40)
 154          >>> s1 -= s2
 155          >>> s1
 156          {'b': 30}
 157          )�keys)rr�kr
 158  r
 159  r�__isub__�s
 160  �zStruct.__isub__cCs>i}|��D]\}}t|t�r|��}|D]}|||<qq|S)z�Helper function for merge.
 161  
 162          Takes a dictionary whose values are lists and returns a dict with
 163          the elements of each list as keys and the original keys as values.
 164          )�itemsrr�split)r�dataZoutdictr �lst�entryr
 165  r
 166  rZ
 167  __dict_invert�s
 168  
 169  �zStruct.__dict_invertcC�|S�Nr
 170  �rr
 171  r
 172  rr�szStruct.dictcCstt�|��S)z�Return a copy as a Struct.
 173  
 174          Examples
 175          --------
 176          >>> s = Struct(a=10,b=30)
 177          >>> s2 = s.copy()
 178          >>> type(s2) is Struct
 179          True
 180          )rrrr)r
 181  r
 182  rr�s
 183  zStruct.copycCs||vS)ahasattr function available as a method.
 184  
 185          Implemented like has_key.
 186  
 187          Examples
 188          --------
 189          >>> s = Struct(a=10)
 190          >>> s.hasattr('a')
 191          True
 192          >>> s.hasattr('b')
 193          False
 194          >>> s.hasattr('get')
 195          False
 196          r
 197  )rrr
 198  r
 199  rr�szStruct.hasattrcCst�|d|�dS)z�Set whether new attributes can be created in this Struct.
 200  
 201          This can be used to catch typos by verifying that the attribute user
 202          tries to change already exists in this Struct.
 203          rN)rr)rZallowr
 204  r
 205  r�allow_new_attr�szStruct.allow_new_attrNcKs�t|fi|��}dd�}dd�}dd�}dd�}dd�}	t�||�}
 206  |rU|��}d|fd|fd	|fd
 207  |fd|	ffD]\}}
 208  ||��vrL||||
 209  <||=q9|
 210  �|�|��|D]}||vrd||||<qW|
 211  |||||�||<qWdS)
 212  aMerge two Structs with customizable conflict resolution.
 213  
 214          This is similar to :meth:`update`, but much more flexible. First, a
 215          dict is made from data+key=value pairs. When merging this dict with
 216          the Struct S, the optional dictionary 'conflict' is used to decide
 217          what to do.
 218  
 219          If conflict is not given, the default behavior is to preserve any keys
 220          with their current value (the opposite of the :meth:`update` method's
 221          behavior).
 222  
 223          Parameters
 224          ----------
 225          __loc_data__ : dict, Struct
 226              The data to merge into self
 227          __conflict_solve : dict
 228              The conflict policy dict.  The keys are binary functions used to
 229              resolve the conflict and the values are lists of strings naming
 230              the keys the conflict resolution function applies to.  Instead of
 231              a list of strings a space separated string can be used, like
 232              'a b c'.
 233          **kw : dict
 234              Additional key, value pairs to merge in
 235  
 236          Notes
 237          -----
 238          The `__conflict_solve` dict is a dictionary of binary functions which will be used to
 239          solve key conflicts.  Here is an example::
 240  
 241              __conflict_solve = dict(
 242                  func1=['a','b','c'],
 243                  func2=['d','e']
 244              )
 245  
 246          In this case, the function :func:`func1` will be used to resolve
 247          keys 'a', 'b' and 'c' and the function :func:`func2` will be used for
 248          keys 'd' and 'e'.  This could also be written as::
 249  
 250              __conflict_solve = dict(func1='a b c',func2='d e')
 251  
 252          These functions will be called for each key they apply to with the
 253          form::
 254  
 255              func1(self['a'], other['a'])
 256  
 257          The return value is used as the final merged value.
 258  
 259          As a convenience, merge() provides five (the most commonly needed)
 260          pre-defined policies: preserve, update, add, add_flip and add_s. The
 261          easiest explanation is their implementation::
 262  
 263              preserve = lambda old,new: old
 264              update   = lambda old,new: new
 265              add      = lambda old,new: old + new
 266              add_flip = lambda old,new: new + old  # note change of order!
 267              add_s    = lambda old,new: old + ' ' + new  # only for str!
 268  
 269          You can use those four words (as strings) as keys instead
 270          of defining them as functions, and the merge method will substitute
 271          the appropriate functions for you.
 272  
 273          For more complicated conflict resolution policies, you still need to
 274          construct your own functions.
 275  
 276          Examples
 277          --------
 278          This show the default policy:
 279  
 280          >>> s = Struct(a=10,b=30)
 281          >>> s2 = Struct(a=20,c=40)
 282          >>> s.merge(s2)
 283          >>> sorted(s.items())
 284          [('a', 10), ('b', 30), ('c', 40)]
 285  
 286          Now, show how to specify a conflict dict:
 287  
 288          >>> s = Struct(a=10,b=30)
 289          >>> s2 = Struct(a=20,b=40)
 290          >>> conflict = {'update':'a','add':'b'}
 291          >>> s.merge(s2,conflict)
 292          >>> sorted(s.items())
 293          [('a', 20), ('b', 70)]
 294          cSr'r(r
 295  ��old�newr
 296  r
 297  r�<lambda>`�zStruct.merge.<locals>.<lambda>cSs|Sr(r
 298  r+r
 299  r
 300  rr.ar/cSs||Sr(r
 301  r+r
 302  r
 303  rr.b�cSs||Sr(r
 304  r+r
 305  r
 306  rr.cr0cSs|d|S)N� r
 307  r+r
 308  r
 309  rr.ds�preserve�update�add�add_flip�add_sN)r�fromkeysrrr3�_Struct__dict_invert)rZ__loc_data__Z_Struct__conflict_solver	Z	data_dictr2r3r4r5r6Zconflict_solveZinv_conflict_solve_user�name�funcrr
 310  r
 311  rrs.U���zStruct.merge)T)NN)�__name__�
 312  __module__�__qualname__�__doc__rrr
 313  rrrrrr!r8rrrr*rr
 314  r
 315  r
 316  rrs""
 317  N)r>�__all__rrr
 318  r
 319  r
 320  r�<module>s