
    .Ph
                        d Z ddlmZmZmZ ddlmZ 	 ddlmZ  ed          Z	n# e
$ r  e            Z	Y nw xY w ed          \  ZZZZZZg d	Z G d
 de          ZeZeZ G d de          Z e            Z e            Z G d de          Z e            Z G d d          ZddZ G d de          Z  G d de          Z!dS )a^  Python has a very powerful mapping type at its core: the :class:`dict`
type. While versatile and featureful, the :class:`dict` prioritizes
simplicity and performance. As a result, it does not retain the order
of item insertion [1]_, nor does it store multiple values per key. It
is a fast, unordered 1:1 mapping.

The :class:`OrderedMultiDict` contrasts to the built-in :class:`dict`,
as a relatively maximalist, ordered 1:n subtype of
:class:`dict`. Virtually every feature of :class:`dict` has been
retooled to be intuitive in the face of this added
complexity. Additional methods have been added, such as
:class:`collections.Counter`-like functionality.

A prime advantage of the :class:`OrderedMultiDict` (OMD) is its
non-destructive nature. Data can be added to an :class:`OMD` without being
rearranged or overwritten. The property can allow the developer to
work more freely with the data, as well as make more assumptions about
where input data will end up in the output, all without any extra
work.

One great example of this is the :meth:`OMD.inverted()` method, which
returns a new OMD with the values as keys and the keys as values. All
the data and the respective order is still represented in the inverted
form, all from an operation which would be outright wrong and reckless
with a built-in :class:`dict` or :class:`collections.OrderedDict`.

The OMD has been performance tuned to be suitable for a wide range of
usages, including as a basic unordered MultiDict. Special
thanks to `Mark Williams`_ for all his help.

.. [1] As of 2015, `basic dicts on PyPy are ordered
   <http://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html>`_,
   and as of December 2017, `basic dicts in CPython 3 are now ordered
   <https://mail.python.org/pipermail/python-dev/2017-December/151283.html>`_, as
   well.
.. _Mark Williams: https://github.com/markrwilliams

    )KeysView
ValuesView	ItemsView)zip_longest   )make_sentinel_MISSING)var_name   )	MultiDictOMDOrderedMultiDictOneToOne
ManyToManysubdict
FrozenDictc                       e Zd ZdZ fdZ fdZd Zd Zd Zd Z	 fdZ
 fd	Zd0 fd	Zef fd	Z fdZef fd	Zd Zed0d            Zd Zd Z fdZ fdZ fdZd Zd Zd ZefdZef fd	Zeef fd	Zd Zd Z d1dZ!d1d Z"d1d!Z#d1d"Z$d2d#Z%d2 fd$	Z&d% Z' fd&Z(d1d'Z)d1d(Z*d1d)Z+d* Z, fd+Z-d, Z.d- Z/d. Z0d/ Z1 xZ2S )3r   a	  A MultiDict is a dictionary that can have multiple values per key
    and the OrderedMultiDict (OMD) is a MultiDict that retains
    original insertion order. Common use cases include:

      * handling query strings parsed from URLs
      * inverting a dictionary to create a reverse index (values to keys)
      * stacking data from multiple dictionaries in a non-destructive way

    The OrderedMultiDict constructor is identical to the built-in
    :class:`dict`, and overall the API constitutes an intuitive
    superset of the built-in type:

    >>> omd = OrderedMultiDict()
    >>> omd['a'] = 1
    >>> omd['b'] = 2
    >>> omd.add('a', 3)
    >>> omd.get('a')
    3
    >>> omd.getlist('a')
    [1, 3]

    Some non-:class:`dict`-like behaviors also make an appearance,
    such as support for :func:`reversed`:

    >>> list(reversed(omd))
    ['b', 'a']

    Note that unlike some other MultiDicts, this OMD gives precedence
    to the most recent value added. ``omd['a']`` refers to ``3``, not
    ``1``.

    >>> omd
    OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)])
    >>> omd.poplast('a')
    3
    >>> omd
    OrderedMultiDict([('a', 1), ('b', 2)])
    >>> omd.pop('a')
    1
    >>> omd
    OrderedMultiDict([('b', 2)])

    If you want a safe-to-modify or flat dictionary, use
    :meth:`OrderedMultiDict.todict()`.

    >>> from pprint import pprint as pp  # preserve printed ordering
    >>> omd = OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)])
    >>> pp(omd.todict())
    {'a': 3, 'b': 2}
    >>> pp(omd.todict(multi=True))
    {'a': [1, 3], 'b': [2]}

    With ``multi=False``, items appear with the keys in to original
    insertion order, alongside the most-recently inserted value for
    that key.

    >>> OrderedMultiDict([('a', 1), ('b', 2), ('a', 3)]).items(multi=False)
    [('a', 3), ('b', 2)]

    .. warning::

       ``dict(omd)`` changed behavior `in Python 3.7
       <https://bugs.python.org/issue34320>`_ due to changes made to
       support the transition from :class:`collections.OrderedDict` to
       the built-in dictionary being ordered. Before 3.7, the result
       would be a new dictionary, with values that were lists, similar
       to ``omd.todict(multi=True)`` (but only shallow-copy; the lists
       were direct references to OMD internal structures). From 3.7
       onward, the values became singular, like
       ``omd.todict(multi=False)``. For reliable cross-version
       behavior, just use :meth:`~OrderedMultiDict.todict()`.

    c                 r    t                                          |           }|                                 |S N)super__new__	_clear_ll)clsakwret	__class__s       Q/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/boltons/dictutils.pyr   zOrderedMultiDict.__new__   s*    ggooc""
    c                 0   t          |          dk    r+t          | j        j        dt          |                    t	                                                       |r|                     |d                    |r|                     |           d S d S )Nr   z" expected at most 1 argument, got r   )len	TypeErrorr   __name__r   __init__update_extendupdate)selfargskwargsr   s      r   r$   zOrderedMultiDict.__init__   s    t99q==#~666D			C D D D 	(tAw''' 	 KK	  	 r   c                 H    t          |                     d                    S )NTmultilist	iteritemsr'   s    r   __getstate__zOrderedMultiDict.__getstate__   s    DNNN..///r   c                 X    |                                   |                     |           d S r   )clearr%   )r'   states     r   __setstate__zOrderedMultiDict.__setstate__   s)    

5!!!!!r   c                     	 | j         }n # t          $ r i x}| _         g | _        Y nw xY w|                                 | j        | j        d g| j        d d <   d S r   _mapAttributeErrorrootr3   r'   r8   s     r   r   zOrderedMultiDict._clear_ll   so    	9DD 	 	 	!!D49DIII	 	

	49d3	!!!   
 ''c                     | j         }| j                            |g           }|t                   }||||g}|x|t          <   |t          <   |                    |           d S r   )r:   r8   
setdefaultPREVNEXTappend)r'   kvr:   cellslastcells          r   _insertzOrderedMultiDict._insert   sa    y	$$Q++DzdAq!"&&T
T$ZTr   c                     t                                          |g           }|                     ||           |                    |           dS )zaAdd a single value *v* under a key *k*. Existing values under *k*
        are preserved.
        N)r   r>   rG   rA   )r'   rB   rC   valuesr   s       r   addzOrderedMultiDict.add   sJ     ##Ar**Qar   c                     |sdS | j         }t                                          |g           }|D ]} |||           |                    |           dS )a  Add an iterable of values underneath a specific key, preserving
        any values already under that key.

        >>> omd = OrderedMultiDict([('a', -1)])
        >>> omd.addlist('a', range(3))
        >>> omd
        OrderedMultiDict([('a', -1), ('a', 0), ('a', 1), ('a', 2)])

        Called ``addlist`` for consistency with :meth:`getlist`, but
        tuples and other sequences and iterables work.
        N)rG   r   r>   extend)r'   rB   rC   self_insertrI   subvr   s         r   addlistzOrderedMultiDict.addlist   sn      	Fl##Ar** 	! 	!DK4    ar   Nc                 V    t                                          ||g          d         S )a  Return the value for key *k* if present in the dictionary, else
        *default*. If *default* is not given, ``None`` is returned.
        This method never raises a :exc:`KeyError`.

        To get all values under a key, use :meth:`OrderedMultiDict.getlist`.
        )r   getr'   rB   defaultr   s      r   rR   zOrderedMultiDict.get   s$     ww{{1wi((,,r   c                     	 t                                          |          dd         S # t          $ r |t          u rg cY S |cY S w xY w)zGet all values for key *k* as a list, if *k* is in the
        dictionary, else *default*. The list returned is a copy and
        can be safely mutated. If *default* is not given, an empty
        :class:`list` is returned.
        N)r   __getitem__KeyErrorr	   rS   s      r   getlistzOrderedMultiDict.getlist   sa    	77&&q))!!!,, 	 	 	(""			NNN	s   (, AAAc                 p    t                                                       |                                  dS )zEmpty the dictionary.N)r   r3   r   )r'   r   s    r   r3   zOrderedMultiDict.clear   s*    r   c                 v    t                                          |          s|t          u rdn|| |<   | |         S )zIf key *k* is in the dictionary, return its value. If not, insert
        *k* with a value of *default* and return *default*. *default*
        defaults to ``None``. See :meth:`dict.setdefault` for more
        information.
        N)r   __contains__r	   rS   s      r   r>   zOrderedMultiDict.setdefault   s?     ww##A&& 	?%11ddwDGAwr   c                 T    |                      |                     d                    S )z(Return a shallow copy of the dictionary.Tr+   r   r/   r0   s    r   copyzOrderedMultiDict.copy	  s"    ~~dnn4n88999r   c                 2     | fd|D                       S )zCreate a dictionary from a list of keys, with all the values
        set to *default*, or ``None`` if *default* is not set.
        c                     g | ]}|fS  ra   ).0rB   rT   s     r   
<listcomp>z-OrderedMultiDict.fromkeys.<locals>.<listcomp>  s    ///QQL///r   ra   )r   keysrT   s     `r   fromkeyszOrderedMultiDict.fromkeys  s*    
 s////$///000r   c                    || u rdS | j         }t          |t                    r5|D ]	}|| v r| |= 
|                    d          D ]\  }} |||           nt	          t          |dd                    r#|                                D ]}||         | |<   n?t                      }|j         }|D ]'\  }}||vr|| v r| |=  ||            |||           (|D ]}||         | |<   dS )zAdd items from a dictionary or iterable (and/or keyword arguments),
        overwriting values under an existing key. See
        :meth:`dict.update` for more details.
        NTr+   rd   )rJ   
isinstancer   r/   callablegetattrrd   set)r'   EFself_addrB   rC   seenseen_adds           r   r&   zOrderedMultiDict.update  sH    99F8a)** 	    99Q$//  1Aga..// 
	VVXX  A$Q 55DxH  1D==Q$YYQHQKKKA 	 	AdDGGr   c                 H   | u r"t                                                    }n_t          t                    r                    d          }n3t          d          r!fd                                D             }n}| j        }|D ]\  }} |||           dS )zAdd items from a dictionary, iterable, and/or keyword
        arguments without overwriting existing items present in the
        dictionary. Like :meth:`update`, but adds to existing keys
        instead of overwriting them.
        Tr+   rd   c              3   ,   K   | ]}||         fV  d S r   ra   )rb   rB   rk   s     r   	<genexpr>z1OrderedMultiDict.update_extend.<locals>.<genexpr>=  s+      44aAaD	444444r   N)iteritemsrg   r   r/   hasattrrd   rJ   )r'   rk   rl   iteratorrm   rB   rC   s    `     r   r%   zOrderedMultiDict.update_extend2  s     99AGGIIHH+,, 	{{{..HHQ 	444416688444HHH8 	 	DAqHQNNNN	 	r   c                     t                                          |          r|                     |           |                     ||           t                                          ||g           d S r   )r   r[   _remove_allrG   __setitem__)r'   rB   rC   r   s      r   ry   zOrderedMultiDict.__setitem__E  sg    77"" 	 QQAs#####r   c                 R    t                                          |          d         S )NrQ   )r   rV   r'   rB   r   s     r   rV   zOrderedMultiDict.__getitem__K  s     ww""1%%b))r   c                 t    t                                          |           |                     |           d S r   )r   __delitem__rx   r{   s     r   r}   zOrderedMultiDict.__delitem__N  s5    Ar   c                 L   | |u rdS 	 t          |          t          |           k    rdS n# t          $ r Y dS w xY wt          |t                    r|                     d          }|                    d          }t          ||d          }|D ]\  \  }}\  }}||k    s||k    r dS t          |t                    t          u rt          |t                    t          u sdS dS t          |d          r,| D ]'}	 ||         | |         k     # t          $ r Y  dS w xY wdS dS )NTFr+   NN)	fillvaluerd   )
r!   r"   rg   r   r/   r   nextr	   ru   rW   )	r'   otherselfiotherizipped_itemsselfkselfvotherkothervs	            r   __eq__zOrderedMultiDict.__eq__R  s}   5==4	5zzSYY&&u ' 	 	 	55	e-.. 	NNN..E__4_00F&ufMMML4@ ! !0 0F??evoo 55 '6x((H44FH--99u4UF## 	 ! !!%LDK/// ! ! ! 555!4us    + 
99=D
DDc                     | |k     S r   ra   r'   r   s     r   __ne__zOrderedMultiDict.__ne__o  s    EM""r   c                 0    |                      |           | S r   )r&   r   s     r   __ior__zOrderedMultiDict.__ior__r  s    Er   c                     	 |                      |          d         S # t          $ r |t          u rt          |          Y nw xY w|S )zRemove all values under key *k*, returning the most-recently
        inserted value. Raises :exc:`KeyError` if the key is not
        present and no *default* is provided.
        rQ   )popallrW   r	   )r'   rB   rT   s      r   popzOrderedMultiDict.popv  s]    
	";;q>>"%% 	" 	" 	"(""qkk! #"	" s    "AAc                     t                      }|                    |          r|                     |           |t          u r|                    |          S |                    ||          S )zRemove all values under key *k*, returning them in the form of
        a list. Raises :exc:`KeyError` if the key is not present and no
        *default* is provided.
        )r   r[   rx   r	   r   )r'   rB   rT   
super_selfr   s       r   r   zOrderedMultiDict.popall  si    
 WW
""1%% 	 Qh>>!$$$~~a)))r   c                    |t           u rJ| r| j        t                   t                   }n*|t           u rt	          dt          |           z            |S 	 |                     |           n*# t          $ r |t           u rt	          |          |cY S w xY wt                                          |          }|	                                }|s!t                      
                    |           |S )aE  Remove and return the most-recently inserted value under the key
        *k*, or the most-recently inserted key if *k* is not
        provided. If no values remain under *k*, it will be removed
        from the OMD.  Raises :exc:`KeyError` if *k* is not present in
        the dictionary, or the dictionary is empty.
        zempty %r)r	   r:   r?   KEYrW   type_remover   rV   r   r}   )r'   rB   rT   rI   rC   r   s        r   poplastzOrderedMultiDict.poplast  s     == IdOC(h&&":T

#:;;;	LLOOOO 	 	 	(""qkk!NNN	 $$Q''JJLL 	#GG"""s   A, ,$BBc                     | j         |         }|                                }|t                   |t                   c|t                   t          <   |t                   t          <   |s
| j         |= d S d S r   r8   r   r@   r?   r'   rB   rI   rF   s       r   r   zOrderedMultiDict._remove  s_    1zz||-1$Zd*T
4$t*T* 		!	 	r   c                     | j         |         }|rW|                                }|t                   |t                   c|t                   t          <   |t                   t          <   |W| j         |= d S r   r   r   s       r   rx   zOrderedMultiDict._remove_all  sc    1 	H::<<D15dT$Z.DJtd4j.  	H IaLLLr   Fc              #      K   | j         }|t                   }|r5||ur/|t                   |t                   fV  |t                   }||u-dS dS |                                 D ]}|| |         fV  dS )zIterate over the OMD's items in insertion order. By default,
        yields only the most-recently inserted value for each key. Set
        *multi* to ``True`` to get all inserted items.
        N)r:   r@   r   VALUEiterkeys)r'   r,   r:   currkeys        r   r/   zOrderedMultiDict.iteritems  s      
 yDz 	%d""3ie,,,,Dz d"""""" }} % %49n$$$$% %r   c              #     K   | j         }|t                   }|r(||ur"|t                   V  |t                   }||u dS dS t                      }|j        }||ur3|t                   }||vr ||           |V  |t                   }||u1dS dS )zIterate over the OMD's keys in insertion order. By default, yields
        each key once, according to the most recent insertion. Set
        *multi* to ``True`` to get all keys, including duplicates, in
        insertion order.
        N)r:   r@   r   rj   rJ   )r'   r,   r:   r   yieldedyielded_addrB   s          r   r   zOrderedMultiDict.iterkeys  s       yDz 	"d""3iDz d"""""" eeG!+Kd""IG##KNNNGGGDz d""""""r   c              #   J   K   |                      |          D ]	\  }}|V  
dS )zIterate over the OMD's values in insertion order. By default,
        yields the most-recently inserted value per unique key.  Set
        *multi* to ``True`` to get all values according to insertion
        order.
        r+   N)r/   )r'   r,   rB   rC   s       r   
itervalueszOrderedMultiDict.itervalues  s>       NNN// 	 	DAqGGGG	 	r   c                 @     |r fd D             S  fd D             S )ap  Gets a basic :class:`dict` of the items in this dictionary. Keys
        are the same as the OMD, values are the most recently inserted
        values for each key.

        Setting the *multi* arg to ``True`` is yields the same
        result as calling :class:`dict` on the OMD, except that all the
        value lists are copies that can be safely mutated.
        c                 <    i | ]}|                     |          S ra   )rX   rb   rB   r'   s     r   
<dictcomp>z+OrderedMultiDict.todict.<locals>.<dictcomp>  s%    5551At||A555r   c                 "    i | ]}||         S ra   ra   r   s     r   r   z+OrderedMultiDict.todict.<locals>.<dictcomp>  s    )))q47)))r   ra   r'   r,   s   ` r   todictzOrderedMultiDict.todict  sA      	655555555))))D))))r   c                 n    | j         } |t          |                     d          ||                    S )a  Similar to the built-in :func:`sorted`, except this method returns
        a new :class:`OrderedMultiDict` sorted by the provided key
        function, optionally reversed.

        Args:
            key (callable): A callable to determine the sort key of
              each element. The callable should expect an **item**
              (key-value pair tuple).
            reverse (bool): Set to ``True`` to reverse the ordering.

        >>> omd = OrderedMultiDict(zip(range(3), range(3)))
        >>> omd.sorted(reverse=True)
        OrderedMultiDict([(2, 2), (1, 1), (0, 0)])

        Note that the key function receives an **item** (key-value
        tuple), so the recommended signature looks like:

        >>> omd = OrderedMultiDict(zip('hello', 'world'))
        >>> omd.sorted(key=lambda i: i[1])  # i[0] is the key, i[1] is the val
        OrderedMultiDict([('o', 'd'), ('l', 'l'), ('e', 'o'), ('l', 'r'), ('h', 'w')])
        Tr+   r   reverse)r   sortedr/   )r'   r   r   r   s       r   r   zOrderedMultiDict.sorted  s8    , ns6$..t.44#wOOOPPPr   c                    	 t                                                      }n0# t          $ r# t                                                      }Y nw xY wfd|D             }|                                 }|                     d          D ]0}|                    |||                                                    1|S )aH  Returns a copy of the :class:`OrderedMultiDict` with the same keys
        in the same order as the original OMD, but the values within
        each keyspace have been sorted according to *key* and
        *reverse*.

        Args:
            key (callable): A single-argument callable to determine
              the sort key of each element. The callable should expect
              an **item** (key-value pair tuple).
            reverse (bool): Set to ``True`` to reverse the ordering.

        >>> omd = OrderedMultiDict()
        >>> omd.addlist('even', [6, 2])
        >>> omd.addlist('odd', [1, 5])
        >>> omd.add('even', 4)
        >>> omd.add('odd', 3)
        >>> somd = omd.sortedvalues()
        >>> somd.getlist('even')
        [2, 4, 6]
        >>> somd.keys(multi=True) == omd.keys(multi=True)
        True
        >>> omd == somd
        False
        >>> somd
        OrderedMultiDict([('even', 2), ('even', 4), ('odd', 1), ('odd', 3), ('even', 6), ('odd', 5)])

        As demonstrated above, contents and key order are
        retained. Only value order changes.
        c                 >    i | ]\  }}|t          |            S )r   )r   )rb   rB   rC   r   r   s      r   r   z1OrderedMultiDict.sortedvalues.<locals>.<dictcomp>-  sF     @ @ @#'1a VA3WFFF @ @ @r   Tr+   )r   r/   r9   rt   r   r   rJ   r   )r'   r   r   superself_iteritemssorted_val_mapr   rB   r   s    ``    r   sortedvalueszOrderedMultiDict.sortedvalues
  s    <	2"'''"3"3"5"5 	2 	2 	2"'''--//	2@ @ @ @ @+>@ @ @nnT** 	0 	0AGGA~a(,,..////
s    & *AAc                 h    |                      d |                     d          D                       S )a  Returns a new :class:`OrderedMultiDict` with values and keys
        swapped, like creating dictionary transposition or reverse
        index.  Insertion order is retained and all keys and values
        are represented in the output.

        >>> omd = OMD([(0, 2), (1, 2)])
        >>> omd.inverted().getlist(2)
        [0, 1]

        Inverting twice yields a copy of the original:

        >>> omd.inverted().inverted()
        OrderedMultiDict([(0, 2), (1, 2)])
        c              3   $   K   | ]\  }}||fV  d S r   ra   rb   rB   rC   s      r   rr   z,OrderedMultiDict.inverted.<locals>.<genexpr>C  s*      LLAq!fLLLLLLr   Tr+   r]   r0   s    r   invertedzOrderedMultiDict.inverted4  s3     ~~LLd1K1KLLLLLLr   c                 n    t                      j        |                     fd| D                       S )zReturns a mapping from key to number of values inserted under that
        key. Like :py:class:`collections.Counter`, but returns a new
        :class:`OrderedMultiDict`.
        c              3   L   K   | ]}|t           |                    fV  d S r   r!   )rb   rB   super_getitems     r   rr   z*OrderedMultiDict.counts.<locals>.<genexpr>M  s:      GGQq#mmA&6&6"7"78GGGGGGr   )r   rV   r   )r'   r   r   s    @r   countszOrderedMultiDict.countsE  s9     +~~GGGG$GGGGGGr   c                 H    t          |                     |                    S )ztReturns a list containing the output of :meth:`iterkeys`.  See
        that method's docs for more details.
        r+   )r.   r   r   s     r   rd   zOrderedMultiDict.keysO  s      DMMM..///r   c                 H    t          |                     |                    S )zvReturns a list containing the output of :meth:`itervalues`.  See
        that method's docs for more details.
        r+   )r.   r   r   s     r   rI   zOrderedMultiDict.valuesU  s      DOO%O00111r   c                 H    t          |                     |                    S )zuReturns a list containing the output of :meth:`iteritems`.  See
        that method's docs for more details.
        r+   r-   r   s     r   rt   zOrderedMultiDict.items[  s      DNNN//000r   c                 *    |                                  S r   )r   r0   s    r   __iter__zOrderedMultiDict.__iter__a  s    }}r   c              #   ,  K   | j         }|t                   }i }|j        }t                      j        }||ur\|t
                   } ||          } ||d          t          |          k    r|V  ||xx         dz  cc<   |t                   }||uZd S d S )Nr   )r:   r?   r>   r   rV   r   r!   )	r'   r:   r   lengths
lengths_sd
get_valuesrB   valsr   s	           r   __reversed__zOrderedMultiDict.__reversed__d  s      yDz'
WW(
$S	A:a==Dz!Q3t99,,AJJJ!OJJJ:D $r   c                     | j         j        }d                    d |                     d          D                       }| d| dS )Nz, c                 6    g | ]\  }}t          ||f          S ra   )reprr   s      r   rc   z-OrderedMultiDict.__repr__.<locals>.<listcomp>t  s&    MMM$!Qq!fMMMr   Tr+   z([z]))r   r#   joinr/   )r'   cnkvss      r   __repr__zOrderedMultiDict.__repr__r  sQ    ^$iiMM$..t.2L2LMMMNNr   c                      t          |           S )zBOMD.viewkeys() -> a set-like object providing a view on OMD's keys)r   r0   s    r   viewkeyszOrderedMultiDict.viewkeysw  s    ~~r   c                      t          |           S )z>OMD.viewvalues() -> an object providing a view on OMD's values)r   r0   s    r   
viewvalueszOrderedMultiDict.viewvalues{  s    $r   c                      t          |           S )zDOMD.viewitems() -> a set-like object providing a view on OMD's items)r   r0   s    r   	viewitemszOrderedMultiDict.viewitems  s    r   r   F)NF)3r#   
__module____qualname____doc__r   r$   r1   r5   r   rG   rJ   rO   rR   r	   rX   r3   r>   r^   classmethodre   r&   r%   ry   rV   r}   r   r   r   r   r   r   r   rx   r/   r   r   r   r   r   r   r   rd   rI   rt   r   r   r   r   r   r   __classcell__r   s   @r   r   r   V   s       H HR    
	  	  	  	  	 0 0 0" " "4 4 4          (- - - - - - "*          
 %-      : : : 1 1 1 [1  <  &$ $ $ $ $* * * * *      :# # #   & 
 
 
 
 !) 
* 
* 
* 
* 
* 
* !(      4    % % % %" " " ",   * * * *Q Q Q Q2( ( ( ( ( (TM M M"H H H H H0 0 0 02 2 2 21 1 1 1           
             r   r   c                   @    e Zd ZdZd Zd Zd Zd ZddZddZ	d	 Z
d
S )FastIterOrderedMultiDictzAn OrderedMultiDict backed by a skip list.  Iteration over keys
    is faster and uses constant memory but adding duplicate key-value
    pairs is slower. Brainchild of Mark Williams.
    c                     	 | j         }n # t          $ r i x}| _         g | _        Y nw xY w|                                 | j        | j        d d | j        | j        g| j        d d <   d S r   r7   r;   s     r   r   z"FastIterOrderedMultiDict._clear_ll  s}    	9DD 	 	 	!!D49DIII	 	

	49d	49.	!!!r<   c                 8   | j         }g }| j                            ||          }|t                   }||u rv||||||g}|t                   t
                   |u r||t                   t
          <   |x|t          <   x|t
          <   x|t          <   |t          <   |                    |           d S |t                   t
                   |ur|t                   n|}||||||g}||t
          <   |x|t          <   x|t          <   |t          <   |                    |           d S r   )r:   r8   r>   r?   SPREVSNEXTr@   rA   )	r'   rB   rC   r:   emptyrD   rE   rF   sprevs	            r   rG   z FastIterOrderedMultiDict._insert  s#   y	$$Q..DzE>>$q$ D E{5!T))%)UE"BFFDJFeFtDzDKLL %)K$6d$B$BDKKE$q4!D DK488DJ8dd5kLLr   c                 v   | j         |         }|                                }|s(| j         |= |t                   |t                   t          <   |t                   t                   t                   |u r,|t
                   |t                   t                   t          <   n[|t                   |t
                   u rA|t                   |t                   c|t                   t          <   |t                   t          <   |t
                   |t                   c|t                   t
          <   |t
                   t          <   d S r   )r8   r   r   r?   r   r@   r'   rB   rD   rF   s       r   r   z FastIterOrderedMultiDict._remove  s    	!yy{{ 	,	! $UDJu:eU#t++'+DzDJue$$%[DJ&&59%[$u+2DKUE 2-1$Zd*T
4$t*T***r   c                    | j                             |          }|r|                                }|t                   t                   t                   |u r,|t
                   |t                   t                   t          <   n[|t                   |t
                   u rA|t                   |t                   c|t                   t          <   |t                   t          <   |t
                   |t                   c|t                   t
          <   |t
                   t          <   ||t                   |t                   t          <   d S r   )r8   r   r?   r   r   r@   r   s       r   rx   z$FastIterOrderedMultiDict._remove_all  s    	a   	H99;;DDz% '4//+/:T
5!%((eT
**9=ed5k6UE"DK$615dT$Z.DJtd4j.  	H !KT
5r   Fc              #      K   |rt           nt          }| j        }||         }||ur*|t                   |t                   fV  ||         }||u(d S d S r   )r@   r   r:   r   r   r'   r,   	next_linkr:   r   s        r   r/   z"FastIterOrderedMultiDict.iteritems  sj      !,DDu	yI$s)T%[((((	?D $r   c              #      K   |rt           nt          }| j        }||         }||ur|t                   V  ||         }||ud S d S r   )r@   r   r:   r   r   s        r   r   z!FastIterOrderedMultiDict.iterkeys  s^      !,DDu	yI$s)OOO	?D $r   c              #      K   | j         }|t                   }||urO|t                   t                   |ur|t                   }||u rd S |t                   V  |t                   }||uMd S d S r   )r:   r?   r   r   r   )r'   r:   r   s      r   r   z%FastIterOrderedMultiDict.__reversed__  s{      yDz$E{5!--E{4<<Es)OOO:D $r   Nr   )r#   r   r   r   r   rG   r   rx   r/   r   r   ra   r   r   r   r     s         
. 
. 
.  6D D D
( 
( 
(# # # ## # # #	 	 	 	 	r   r   c                   n    e Zd ZdZdZd Zed             Zd Zd Z	d Z
d Zefd	Zd
 ZddZd Zd ZdS )r   a  Implements a one-to-one mapping dictionary. In addition to
    inheriting from and behaving exactly like the builtin
    :class:`dict`, all values are automatically added as keys on a
    reverse mapping, available as the `inv` attribute. This
    arrangement keeps key and value namespaces distinct.

    Basic operations are intuitive:

    >>> oto = OneToOne({'a': 1, 'b': 2})
    >>> print(oto['a'])
    1
    >>> print(oto.inv[1])
    a
    >>> len(oto)
    2

    Overwrites happens in both directions:

    >>> oto.inv[1] = 'c'
    >>> print(oto.get('a'))
    None
    >>> len(oto)
    2

    For a very similar project, with even more one-to-one
    functionality, check out `bidict <https://github.com/jab/bidict>`_.
    )invc                 J   d}|ru|d         t           u rK|d         | _        t                              | d | j                                        D                        d S |d         t
          u r|dd          d}}t          j        | g|R i | |                     t           |           | _        t          |           t          | j                  k    rd S |sXt                              |            t          	                    | d | j                                        D                        d S i }|                                 D ].\  }}|
                    |g                               |           /d |                                D             }t          d|z            )	NFr   r   c                     g | ]	\  }}||f
S ra   ra   r   s      r   rc   z%OneToOne.__init__.<locals>.<listcomp>  s     $I$I$I1aV$I$I$Ir   Tc                     g | ]	\  }}||f
S ra   ra   r   s      r   rc   z%OneToOne.__init__.<locals>.<listcomp>   s     CCC$!Q1vCCCr   c                 @    i | ]\  }}t          |          d k    ||S )r   r   )rb   rC   k_lists      r   r   z%OneToOne.__init__.<locals>.<dictcomp>)  s7     @ @ @yq&/26{{Q F/>r   zFexpected unique values, got multiple keys for the following values: %r)_OTO_INV_MARKERr   dictr$   rt   _OTO_UNIQUE_MARKERr   r!   r3   r&   r>   rA   
ValueError)r'   r   r   raise_on_dupeval_multidictrB   rC   dupess           r   r$   zOneToOne.__init__  s    	/t&&Q4d$I$I8H8H$I$I$IJJJ1+++#$QRR5$=d%Q%%%"%%%>>/488t99DH%%F 	JJtKKCC$(..2B2BCCCDDDF JJLL 	6 	6DAq$$Q++2215555@ @#))++@ @ @  57<= > > 	>r   c                 $     | t           g|R i |S )a>  This alternate constructor for OneToOne will raise an exception
        when input values overlap. For instance:

        >>> OneToOne.unique({'a': 1, 'b': 1})
        Traceback (most recent call last):
        ...
        ValueError: expected unique values, got multiple keys for the following values: ...

        This even works across inputs:

        >>> a_dict = {'a': 2}
        >>> OneToOne.unique(a_dict, b=2)
        Traceback (most recent call last):
        ...
        ValueError: expected unique values, got multiple keys for the following values: ...
        )r   )r   r   r   s      r   uniquezOneToOne.unique/  s%    $ s%0000R000r   c                    t          |           || v r&t                              | j        | |                    || j        v r| j        |= t                              | ||           t                              | j        ||           d S r   )hashr   r}   r   ry   r'   r   vals      r   ry   zOneToOne.__setitem__C  s~    S			$;;TXtCy111$(??sC(((3,,,,,r   c                     t                               | j        | |                    t                               | |           d S r   )r   r}   r   r'   r   s     r   r}   zOneToOne.__delitem__L  s:    49---s#####r   c                 x    t                               |            t                               | j                   d S r   )r   r3   r   r0   s    r   r3   zOneToOne.clearP  s.    

4

48r   c                 ,    |                      |           S r   r   r0   s    r   r^   zOneToOne.copyT  s    ~~d###r   c                     || v rAt                               | j        | |                    t                               | |          S |t          ur|S t                      r   )r   r}   r   r   r	   rW   r'   r   rT   s      r   r   zOneToOne.popW  sU    $;;TXtCy11188D#&&&(""Njjr   c                     t                               |           \  }}t                               | j        |           ||fS r   )r   popitemr}   r   r  s      r   r  zOneToOne.popitem_  s8    <<%%S3'''Cxr   Nc                 $    || vr|| |<   | |         S r   ra   r	  s      r   r>   zOneToOne.setdefaultd  s    d??DICyr   c                    g }t          |t                    rH|                                D ]2}t          |           t	          |                                          }3n5|D ]2\  }}t          |           t          |           t	          |          }3|                                D ]}t          |           |                    |                                           |D ]
\  }}|| |<   d S r   )rg   r   rI   r  r.   rt   rL   )r'   dict_or_iterabler   	keys_valsr  r   s         r   r&   zOneToOne.updatei  s   	&-- 	3'..00 ; ;S			 !1!7!7!9!9::		; - 3 3SS			S			 !122		99;; 	 	CIIII$$$! 	 	HCDII	 	r   c                 ^    | j         j        }t                              |           }| d| dS N()r   r#   r   r   )r'   r   	dict_reprs      r   r   zOneToOne.__repr__z  s4    ^$MM$''	##y####r   r   )r#   r   r   r   	__slots__r$   r   r   ry   r}   r3   r^   r	   r   r  r>   r&   r   ra   r   r   r   r     s         6 I >  >  >D 1 1 [1&- - -$ $ $  $ $ $  (      
   
  "$ $ $ $ $r   r   c                       e Zd ZdZddZ e            fdZd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd ZdS )r   a3  
    a dict-like entity that represents a many-to-many relationship
    between two groups of objects

    behaves like a dict-of-tuples; also has .inv which is kept
    up to date which is a dict-of-tuples in the other direction

    also, can be used as a directed graph among hashable python objects
    Nc                     i | _         t          |          t          u r|r|d         t          u r|d         | _        n8|                     t          | f          | _        |r|                     |           d S )Nr   r   )datar   tuple_PAIRINGr   r   r&   )r'   rt   s     r   r$   zManyToMany.__init__  sq    	;;%EeAh(.B.BQxDHH~~x&677DH #E"""r   c                 8    	 | |         S # t           $ r |cY S w xY wr   )rW   r	  s      r   rR   zManyToMany.get  s5    	9 	 	 	NNN	s   
 c                 6    t          | j        |                   S r   )	frozensetr  r  s     r   rV   zManyToMany.__getitem__  s    3(((r   c                     t          |          }|| v r;| j        |         |z
  }|| j        |         z  }|D ]}|                     ||           |D ]}|                     ||           d S r   )rj   r  removerJ   )r'   r   r   	to_remover  s        r   ry   zManyToMany.__setitem__  s    4yy$;;	#-IDIcN"D  & &C%%%% 	 	CHHS#	 	r   c                     | j                             |          D ]F}| j        j         |                             |           | j        j         |         s| j        j         |= Gd S r   )r  r   r   r   r  s      r   r}   zManyToMany.__delitem__  sd    9==%% 	' 	'CHM#%%c***8=% 'HM#&	' 	'r   c                    t          |          t          |           u r|}|j        D ]L}|| j        vr|j        |         | j        |<   !| j        |                             |j        |                    M|j        j        D ]e}|| j        j        vr |j        j        |         | j        j        |<   0| j        j        |                             |j        j        |                    fnpt	          t          |dd                    r4|                                D ]}|                     |||                    n|D ]\  }}|                     ||           dS )z-given an iterable of (key, val), add them allrd   N)r   r  r&   r   rh   ri   rd   rJ   )r'   iterabler   rB   r   r  s         r   r&   zManyToMany.update  sb   >>T$ZZ''EZ 7 7DI%%#(:a=DIaLLIaL''
16666Y^ ? ?DHM))',y~a'8DHM!$$HM!$++EIN1,=>>>>	?
 gh5566 	#]]__ ) )HQK(((() % # #Sc""""r   c                     || j         vrt                      | j         |<   | j         |                             |           || j        j         vrt                      | j        j         |<   | j        j         |                             |           d S r   )r  rj   rJ   r   r  s      r   rJ   zManyToMany.add  s|    di UUDIcN	#3dhm##!$DHM#cs#####r   c                     | j         |                             |           | j         |         s| j         |= | j        j         |                             |           | j        j         |         s| j        j         |= d S d S r   )r  r   r   r  s      r   r   zManyToMany.remove  s}    	#c"""y~ 		#c!!#&&&x}S! 	#c"""	# 	#r   c                     || j         vrdS | j                             |          x| j         |<   }|D ]>}| j        j         |         }|                    |           |                    |           ?dS )z4
        replace instances of key by newkey
        N)r  r   r   r   rJ   )r'   r   newkeyfwdsetr  revsets         r   replacezManyToMany.replace  s     diF%)Y]]3%7%77	&F 	 	CX]3'FMM#JJv	 	r   c              #   J   K   | j         D ]}| j         |         D ]}||fV  	d S r   r  r  s      r   r/   zManyToMany.iteritems  sJ      9 	 	Cy~  3h	 	r   c                 4    | j                                         S r   )r  rd   r0   s    r   rd   zManyToMany.keys  s    y~~r   c                     || j         v S r   r-  r  s     r   r[   zManyToMany.__contains__  s    dir   c                 4    | j                                         S r   )r  r   r0   s    r   r   zManyToMany.__iter__  s    y!!###r   c                 4    | j                                         S r   )r  __len__r0   s    r   r2  zManyToMany.__len__  s    y  """r   c                 b    t          |           t          |          k    o| j        |j        k    S r   )r   r  r   s     r   r   zManyToMany.__eq__  s'    DzzT%[[(DTY%*-DDr   c                 h    | j         j        }| dt          |                                           dS r  )r   r#   r.   r/   r'   r   s     r   r   zManyToMany.__repr__  s5    ^$22tDNN,,--2222r   r   )r#   r   r   r   r$   r  rR   rV   ry   r}   r&   rJ   r   r+  r/   rd   r[   r   r2  r   r   ra   r   r   r   r     s&             )y{{    ) ) )  ' ' '  ,$ $ $# # #
 
 
  
          $ $ $# # #E E E3 3 3 3 3r   r   Nc                     ||                                  }|g }t          |          t          |          z
   t          |           fd|                                 D                       S )a  Compute the "subdictionary" of a dict, *d*.

    A subdict is to a dict what a subset is a to set. If *A* is a
    subdict of *B*, that means that all keys of *A* are present in
    *B*.

    Returns a new dict with any keys in *drop* removed, and any keys
    in *keep* still present, provided they were in the original
    dict. *keep* defaults to all keys, *drop* defaults to empty, so
    without one of these arguments, calling this function is
    equivalent to calling ``dict()``.

    >>> from pprint import pprint as pp
    >>> pp(subdict({'a': 1, 'b': 2}))
    {'a': 1, 'b': 2}
    >>> subdict({'a': 1, 'b': 2, 'c': 3}, drop=['b', 'c'])
    {'a': 1}
    >>> pp(subdict({'a': 1, 'b': 2, 'c': 3}, keep=['a', 'c']))
    {'a': 1, 'c': 3}

    Nc                 &    g | ]\  }}|v 	||fS ra   ra   )rb   rB   rC   rd   s      r   rc   zsubdict.<locals>.<listcomp>  s&    >>>tq!AIIQFIIIr   )rd   rj   r   rt   )dkeepdroprd   s      @r   r   r     sj    , |vvxx|t99s4yy D477>>>>qwwyy>>>???r   c                       e Zd ZdS )FrozenHashErrorN)r#   r   r   ra   r   r   r<  r<    s        Dr   r<  c                   t    e Zd ZdZdZd Zedd            Zd Zd Z	d Z
d	 Zd
 ZexZxZxZZexZxZxZZ[dS )r   a  An immutable dict subtype that is hashable and can itself be used
    as a :class:`dict` key or :class:`set` entry. What
    :class:`frozenset` is to :class:`set`, FrozenDict is to
    :class:`dict`.

    There was once an attempt to introduce such a type to the standard
    library, but it was rejected: `PEP 416 <https://www.python.org/dev/peps/pep-0416/>`_.

    Because FrozenDict is a :class:`dict` subtype, it automatically
    works everywhere a dict would, including JSON serialization.

    )_hashc                 j    t          |           } |j        |i |  t          |           |          S )zMake a copy and add items from a dictionary or iterable (and/or
        keyword arguments), overwriting values under an existing
        key. See :meth:`dict.update` for more details.
        )r   r&   r   )r'   r   r   r  s       r   updatedzFrozenDict.updated/  s<    
 DzzQ"tDzz$r   Nc                 J     | t                               ||                    S r   )r   re   )r   rd   values      r   re   zFrozenDict.fromkeys8  s"     s4==u--...r   c                 Z    | j         j        }| dt                              |            dS r  r  r5  s     r   r   zFrozenDict.__repr__=  s/    ^$--t}}T**----r   c                 @    t          |           t          |           ffS r   )r   r   )r'   protocols     r   __reduce_ex__zFrozenDict.__reduce_ex__A  s    DzzDJJ=((r   c                     	 | j         }nt# t          $ rg 	 t          t          |                                                     x}| _         n-# t
          $ r }t          |          x}| _         Y d }~nd }~ww xY wY nw xY w|j        t          u r||S r   )r>  r9   r  r  rt   	Exceptionr<  r   )r'   r   es      r   __hash__zFrozenDict.__hash__D  s    	6*CC 	6 	6 	66#'	$**,,(?(?#@#@@djj 6 6 6#21#5#55djjjjjj6	6 =O++I
s8   
 
A;5A
A;
A5A0+A;0A55A;:A;c                     | S r   ra   r0   s    r   __copy__zFrozenDict.__copy__R  s    r   c                 :    t          d| j        j        z            )z5raises a TypeError, because FrozenDicts are immutablez%s object is immutable)r"   r   r#   )r'   r   r   s      r   _raise_frozen_typeerrorz"FrozenDict._raise_frozen_typeerrorV  s    04>3JJKKKr   r   )r#   r   r   r   r  r@  r   re   r   rF  rJ  rL  rN  r   ry   r}   r&   r>   r   r  r3   ra   r   r   r   r      s          I      / / / [/. . .) ) )    L L L 4KJGJkJK&)@@J@@wr   r   r   )"r   collections.abcr   r   r   	itertoolsr   	typeutilsr   r	   ImportErrorobjectranger?   r@   r   r   r   r   __all__r   r   r   r   r   r   r   r   r  r   r   r"   r<  r   ra   r   r   <module>rV     s5  >% %N < ; ; ; ; ; ; ; ; ; ! ! ! ! ! !((((((}j111HH   vxxHHH (-uQxx $dCu f
e
ek k k k kt k k k^ 	_ _ _ _ _/ _ _ _D &((VXX N$ N$ N$ N$ N$t N$ N$ N$d 688u3 u3 u3 u3 u3 u3 u3 u3p@ @ @ @@	 	 	 	 	i 	 	 	=  =  =  =  =  =  =  =  =  = s   ' 99