
    Vi                        S r  SSKJrJrJr  SSKr SSKJr   SSK
Jr  \" SS9r\" S	5      u  rrrrrr/ S
Qr \   " S S\5      r\r\r " S S\5      r\" 5       r\" 5       r " S S\5      r\" 5       r  " S S\5      r!SS jr" " S S\#5      r$ " S S\5      r%g! \ a    SSKJrJrJr   Nf = f! \ a	    SSKJ	r   Nf = f! \ a
    \" 5       r Nf = f! \ a    S r Nf = f)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	ItemsViewN)izip_longest)zip_longest)make_sentinel_MISSING)var_name   )	MultiDictOMDOrderedMultiDictOneToOne
ManyToManysubdict
FrozenDictc                     U $ N )xs    d/home/james-whalen/.local/share/pipx/venvs/semgrep/lib/python3.13/site-packages/boltons/dictutils.py<lambda>r   c   s        c                     ^  \ rS rSrSrU 4S jrS rS rU 4S jrU 4S jr	S,U 4S jjr
\4U 4S	 jjrU 4S
 jr\4U 4S jjrS r\S,S j5       rS rS rU 4S jrU 4S jrU 4S jrS rS r\4S jr\4U 4S jjr\\4U 4S jjrS rS rS-S jrS-S jrS-S jr S-S jr!S.S jr"S.U 4S jjr#S  r$U 4S! jr%S-S" jr&S-S# jr'S-S$ jr(S% r)U 4S& jr*S' r+S( r,S) r-S* r.S+r/U =r0$ )/r   f   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                 .  > [        U5      S:  a/  [        U R                  R                  < S[        U5      < 35      e[        [
        U ]  5         U R                  5         U(       a  U R                  US   5        U(       a  U R                  U5        g g )N   z" expected at most 1 argument, got r   )
len	TypeError	__class____name__superr   __init__	_clear_llupdate_extendupdate)selfargskwargsr    s      r   r#   OrderedMultiDict.__init__   sw    t9q=#~~66D	C D D.0tAw'KK r   c                      U R                   nUR                  5         U R                  U R                  S /U R                  S S & g ! [         a    0 =ol         / U l         NRf = fr   _mapAttributeErrorrootclearr'   r-   s     r   r$   OrderedMultiDict._clear_ll   sY    	99D 	

		499d3		!	  	!!D9DI	s   A A! A!c                     U R                   nU R                  R                  U/ 5      nU[           nXSX/nU=U[        '   U[        '   UR                  U5        g r   )r/   r-   
setdefaultPREVNEXTappend)r'   kvr/   cellslastcells          r   _insertOrderedMultiDict._insert   sR    yy		$$Q+DzA!"&&T
T$ZTr   c                 r   > [         [        U ]  U/ 5      nU R                  X5        UR	                  U5        g)zQAdd a single value *v* under a key *k*. Existing values under *k*
are preserved.
N)r"   r   r4   r=   r7   )r'   r8   r9   valuesr    s       r   addOrderedMultiDict.add   s1     '9!R@Qar   c                    > U(       d  gU R                   n[        [        U ]  U/ 5      nU H  nU" X5        M     UR	                  U5        g)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)r=   r"   r   r4   extend)r'   r8   r9   self_insertr@   subvr    s         r   addlistOrderedMultiDict.addlist   sF     ll'9!R@D  ar   c                 2   > [         [        U ]  X/5      S   $ )zReturn 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"   r   getr'   r8   defaultr    s      r   rK   OrderedMultiDict.get   s     %t0I>rBBr   c                 p   >  [         [        U ]  U5      SS $ ! [         a    U[        L a  / s $ Us $ f = f)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"   r   __getitem__KeyErrorr	   rL   s      r   getlistOrderedMultiDict.getlist   sA    	)4<Q?BB 	("	N	s    555c                 J   > [         [        U ]  5         U R                  5         g)zEmpty the dictionary.N)r"   r   r0   r$   )r'   r    s    r   r0   OrderedMultiDict.clear   s    +-r   c                 Z   > [         [        U ]  U5      (       d  U[        L a  SOUX'   X   $ )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"   r   __contains__r	   rL   s      r   r4   OrderedMultiDict.setdefault  s/     %t9!<<%1dwDGwr   c                 >    U R                  U R                  SS95      $ )z(Return a shallow copy of the dictionary.Tmultir    	iteritemsr'   s    r   copyOrderedMultiDict.copy  s    ~~dnn4n899r   c                 @    U " U Vs/ s H  o3U4PM     sn5      $ s  snf )ztCreate a dictionary from a list of keys, with all the values
set to *default*, or ``None`` if *default* is not set.
r   )clskeysrM   r8   s       r   fromkeysOrderedMultiDict.fromkeys  s#    
 $/$QL$/00/s   c                    XL a  gU R                   n[        U[        5      (       a3  U H  nX@;   d  M
  X	 M     UR                  SS9 H  u  pEU" XE5        M     Ov[	        [        USS5      5      (       a  UR                  5        H	  nX   X'   M     O=[        5       nUR                   nU H!  u  pEXF;  a  X@;   a
  X	 U" U5        U" XE5        M#     U H	  nX$   X'   M     g)zAdd items from a dictionary or iterable (and/or keyword arguments),
overwriting values under an existing key. See
:meth:`dict.update` for more details.
NTrZ   rc   )rA   
isinstancer   r]   callablegetattrrc   set)r'   EFself_addr8   r9   seenseen_adds           r   r&   OrderedMultiDict.update  s     988a)**9  $/ 0ga.//VVX$  5DxxH=QYQK	 
 AdDG r   c                 (  ^ TU L a  [        TR                  5       5      nOS[        T[        5      (       a  TR	                  SS9nO.[        TS5      (       a  U4S jTR                  5        5       nOTnU R                  nU H  u  pVU" XV5        M     g)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.
TrZ   rc   c              3   0   >#    U  H  oTU   4v   M     g 7fr   r   ).0r8   rk   s     r   	<genexpr>1OrderedMultiDict.update_extend.<locals>.<genexpr>B  s     48aAaD	8s   N)iteritemsrg   r   r]   hasattrrc   rA   )r'   rk   rl   iteratorrm   r8   r9   s    `     r   r%   OrderedMultiDict.update_extend7  sw     9AGGIH+,,{{{.HQ416684HH88DAQN r   c                    > [         [        U ]  U5      (       a  U R                  U5        U R	                  X5        [         [        U ]  X/5        g r   )r"   r   rW   _remove_allr=   __setitem__)r'   r8   r9   r    s      r   r}   OrderedMultiDict.__setitem__J  sB    !45a88QQ1!S9r   c                 0   > [         [        U ]  U5      S   $ )NrJ   )r"   r   rP   r'   r8   r    s     r   rP   OrderedMultiDict.__getitem__P  s    %t8;B??r   c                 N   > [         [        U ]  U5        U R                  U5        g r   )r"   r   __delitem__r|   r   s     r   r   OrderedMultiDict.__delitem__S  s!    1!4r   c                    XL a  g [        U5      [        U 5      :w  a  g [        U[        5      (       at  U R	                  SS9nUR	                  SS9n[        X#SS9nU H  u  u  pVu  pxXW:w  d  Xh:w  d  M    g   [        U[        5      [        L a  [        U[        5      [        L d  gg[        US5      (       a  U  H  n X   X   :H    M     gg! [         a     gf = f! [         a       gf = f)NTFrZ   NN)	fillvaluerc   )
r   r   rg   r   r]   r   nextr	   rx   rQ   )	r'   otherselfiotherizipped_itemsselfkselfvotherkothervs	            r   __eq__OrderedMultiDict.__eq__W  s   =	5zSY& ' e-..NNN.E__4_0F'NL4@0 0?eo  5A x(H4FH-9UF##!LDK/ 
 +  		$   ! !s#   C 	C 
CC 
C.-C.c                     X:X  + $ r   r   r'   r   s     r   __ne__OrderedMultiDict.__ne__t  s    ""r   c                 v     U R                  U5      S   $ ! [         a    U[        L a  [        U5      e U$ f = f)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.
rJ   )popallrQ   r	   )r'   r8   rM   s      r   popOrderedMultiDict.popw  sE    
	";;q>"%% 	"("qk! #	"s    88c                    > [        [        U 5      nUR                  U5      (       a  U R                  U5        U[        L a  UR                  U5      $ UR                  X5      $ )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   rW   r|   r	   r   )r'   r8   rM   
super_selfr    s       r   r   OrderedMultiDict.popall  sW    
 +T2
""1%%Qh>>!$$~~a))r   c                   > U[         L aD  U (       a  U R                  [           [           nO"U[         L a  [	        S[        U 5      -  5      eU$  U R                  U5        [        [        U ]'  U5      nUR                  5       nU(       d  [        [        U ]/  U5        U$ ! [         a    U[         L a  [	        U5      eUs $ f = f)a  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/   r5   KEYrQ   type_remover"   r   rP   r   r   )r'   r8   rM   r@   r9   r    s        r   poplastOrderedMultiDict.poplast  s     =IIdOC(h&":T
#:;;	LLO
 ':1=JJL"D5a8  	("qk!N	s   B    CCc                     U R                   U   nUR                  5       nU[           U[           sU[           [        '   U[           [        '   U(       d  U R                   U	 g g r   r-   r   r6   r5   r'   r8   r@   r<   s       r   r   OrderedMultiDict._remove  sS    1zz|-1$Zd*T
4$t*T*		! r   c                     U R                   U   nU(       aH  UR                  5       nU[           U[           sU[           [        '   U[           [        '   U(       a  MH  U R                   U	 g r   r   r   s       r   r|   OrderedMultiDict._remove_all  sW    1::<D15dT$Z.DJtd4j. f IIaLr   c              #      #    U R                   nU[           nU(       a)  X2La$  U[           U[           4v   U[           nX2La  M#  ggU R	                  5        H  nX@U   4v   M     g7f)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/   r6   r   VALUEiterkeys)r'   r[   r/   currkeys        r   r]   OrderedMultiDict.iteritems  sd     
 yyDz"3ie,,Dz " }}9n$ 's   AA("A(c              #     #    U R                   nU[           nU(       a   X2La  U[           v   U[           nX2La  M  gg[        5       nUR                  nX2La*  U[           nXd;  a  U" U5        Uv   U[           nX2La  M)  gg7f)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/   r6   r   rj   rA   )r'   r[   r/   r   yieldedyielded_addr8   s          r   r   OrderedMultiDict.iterkeys  s      yyDz"3iDz " eG!++K"I#NGDz "s   9BABBc              #   D   #    U R                  US9 H	  u  p#Uv   M     g7f)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.
rZ   N)r]   )r'   r[   r8   r9   s       r   
itervaluesOrderedMultiDict.itervalues  s#      NNN/DAG 0s    c           	          U(       a,  [        U  Vs/ s H  o"U R                  U5      4PM     sn5      $ [        U  Vs/ s H  o"X   4PM
     sn5      $ s  snf s  snf )a@  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.
)dictrR   )r'   r[   r8   s      r   todictOrderedMultiDict.todict  sR     t<t!T\\!_-t<==404a\4011 =0s
   AAc                 T    U R                   nU" [        U R                  SS9XS95      $ )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')])
TrZ   r   reverse)r    sortedr]   )r'   r   r   rb   s       r   r   OrderedMultiDict.sorted  s*    , nn6$..t.4#OPPr   c                 l  >  [         [        U ]  5       n[        U VVs/ s H  u  pEU[        XQU(       + S94PM     snn5      nU R                  5       nU R                  SS9 H%  nUR                  XFU   R                  5       5        M'     U$ ! [         a    [         [        U ]  5       n Nf = fs  snnf )a  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.
r   TrZ   )r"   r   r]   r.   rw   r   r   r    r   rA   r   )	r'   r   r   superself_iteritemsr8   r9   sorted_val_mapretr    s	           r   sortedvaluesOrderedMultiDict.sortedvalues  s    <	H"'(8$"I"K +>@+>41 !"6!7{#LM+>@ AnnT*AGGAa(,,./ +
  	H"'(8$"E"G	H@s   B B0
B-,B-c                 L    U R                  S U R                  SS9 5       5      $ )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   ,   #    U  H
  u  pX!4v   M     g 7fr   r   )rs   r8   r9   s      r   rt   ,OrderedMultiDict.inverted.<locals>.<genexpr>D  s     L1Kqf1Ks   TrZ   r\   r^   s    r   invertedOrderedMultiDict.inverted5  s$     ~~Ld1KLLLr   c                 X   >^ [         [        U ]
  mU R                  U4S jU  5       5      $ )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   H   >#    U  H  o[        T" U5      5      4v   M     g 7fr   )r   )rs   r8   super_getitems     r   rt   *OrderedMultiDict.counts.<locals>.<genexpr>N  s     G$Q#mA&6"78$s   ")r"   r   rP   r    )r'   r   r    s    @r   countsOrderedMultiDict.countsF  s'     .A~~G$GGGr   c                 2    [        U R                  US95      $ )zdReturns a list containing the output of :meth:`iterkeys`.  See
that method's docs for more details.
rZ   )listr   r'   r[   s     r   rc   OrderedMultiDict.keysP  s     DMMM.//r   c                 2    [        U R                  US95      $ )zfReturns a list containing the output of :meth:`itervalues`.  See
that method's docs for more details.
rZ   )r   r   r   s     r   r@   OrderedMultiDict.valuesV  s     DOO%O011r   c                 2    [        U R                  US95      $ )zeReturns a list containing the output of :meth:`iteritems`.  See
that method's docs for more details.
rZ   )r   r]   r   s     r   rw   OrderedMultiDict.items\  s     DNNN/00r   c                 "    U R                  5       $ r   )r   r^   s    r   __iter__OrderedMultiDict.__iter__b  s    }}r   c              #     >#    U R                   nU[           n0 nUR                  n[        [        U ]  nX!LaG  U[           nU" U5      nU" US5      [        U5      :X  a  Uv   X6==   S-  ss'   U[           nX!La  MF  g g 7f)Nr   )r/   r5   r4   r"   r   rP   r   r   )	r'   r/   r   lengths
lengths_sd
get_valuesr8   valsr    s	           r   __reversed__OrderedMultiDict.__reversed__e  s     yyDz''
+T>
S	Aa=D!Q3t9,J!OJ:D s   A:B?Bc           
          U R                   R                  nSR                  U R                  SS9 VVs/ s H  u  p#[	        X#45      PM     snn5      nU< SU< S3$ s  snnf )Nz, TrZ   z([z]))r    r!   joinr]   repr)r'   cnr8   r9   kvss        r   __repr__OrderedMultiDict.__repr__s  sT    ^^$$ii$..t.2LM2L$!qf2LMN%% Ns   A
c                     [        U 5      $ )zBOMD.viewkeys() -> a set-like object providing a view on OMD's keys)r   r^   s    r   viewkeysOrderedMultiDict.viewkeysx  s    ~r   c                     [        U 5      $ )z>OMD.viewvalues() -> an object providing a view on OMD's values)r   r^   s    r   
viewvaluesOrderedMultiDict.viewvalues|  s    $r   c                     [        U 5      $ )zDOMD.viewitems() -> a set-like object providing a view on OMD's items)r   r^   s    r   	viewitemsOrderedMultiDict.viewitems  s    r   r-   r/   r   F)NF)1r!   
__module____qualname____firstlineno____doc__r#   r$   r=   rA   rG   rK   r	   rR   r0   r4   r_   classmethodrd   r&   r%   r}   rP   r   r   r   r   r   r   r   r|   r]   r   r   r   r   r   r   r   rc   r@   rw   r   r   r   r   r   r   __static_attributes____classcell__r    s   @r   r   r   f   s   HR
 4(C "* 
 %- : 1 1<&:@:# & 
 !) 
* !( 4%",2Q2(TM"H021&
  r   r   c                   J    \ rS rSrSrS rS rS rS rSS jr	SS jr
S	 rS
rg)FastIterOrderedMultiDicti  zAn 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                      U R                   nUR                  5         U R                  U R                  S S U R                  U R                  /U R                  S S & g ! [         a    0 =ol         / U l         Nif = fr   r,   r1   s     r   r$   "FastIterOrderedMultiDict._clear_ll  sk    	99D 	

		499d		499.		!	  	!!D9DI	s   A A87A8c                    U R                   n/ nU R                  R                  X5      nU[           nXTL a]  XcXXc/nU[           [
           UL a  Xv[           [
        '   U=U[        '   =U[
        '   =U[        '   U[        '   UR                  U5        g U[           [
           ULa	  U[           OUnXcXX/nX6[
        '   U=U[        '   =U[        '   U[        '   UR                  U5        g r   )r/   r-   r4   r5   SPREVSNEXTr6   r7   )	r'   r8   r9   r/   emptyr:   r;   r<   sprevs	            r   r=    FastIterOrderedMultiDict._insert  s    yy		$$Q.Dz> D E{5!T)%)UE"BFFDJFeFtDzDKLL %)K$6d$BDKE!D K488DJ8dd5kLLr   c                    U R                   U   nUR                  5       nU(       d$  U R                   U	 U[           U[           [        '   U[           [           [           UL a  U[
           U[           [           [        '   OBU[           U[
           L a/  U[           U[           sU[           [        '   U[           [        '   U[
           U[           sU[           [
        '   U[
           [        '   g r   )r-   r   r  r5   r  r6   r'   r8   r:   r<   s       r   r    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                    U R                   R                  U5      nU(       a  UR                  5       nU[           [           [           UL a  U[
           U[           [           [        '   OBU[           U[
           L a/  U[           U[           sU[           [        '   U[           [        '   U[
           U[           sU[           [
        '   U[
           [        '   U(       a  M  W[           U[           [        '   g r   )r-   r   r5   r  r  r6   r  s       r   r|   $FastIterOrderedMultiDict._remove_all  s    		a 99;DDz% '4/+/:T
5!%(eT
*9=ed5k6UE"DK$615dT$Z.DJtd4j. e !KT
5r   c              #      #    U(       a  [         O[        nU R                  nX2   nXCLa  U[           U[           4v   XB   nXCLa  M  g g 7fr   )r6   r  r/   r   r   r'   r[   	next_linkr/   r   s        r   r]   "FastIterOrderedMultiDict.iteritems  sF     !Du	yys)T%[((?D s   AA
A
c              #      #    U(       a  [         O[        nU R                  nX2   nXCLa  U[           v   XB   nXCLa  M  g g 7fr   )r6   r  r/   r   r  s        r   r   !FastIterOrderedMultiDict.iterkeys  s<     !Du	yys)O?D s
   ;AAc              #      #    U R                   nU[           nX!La<  U[           [           ULa  U[           nX!L a  g U[           v   U[           nX!La  M;  g g 7fr   )r/   r5   r  r  r   )r'   r/   r   s      r   r   %FastIterOrderedMultiDict.__reversed__  sY     yyDzE{5!-E{<s)O:D s   AAAr   Nr   )r!   r   r   r   r   r$   r=   r   r|   r]   r   r   r   r   r   r   r   r     s+    
.6D
(##	r   r   c                   r    \ rS rSrSrSrS r\S 5       rS r	S r
S rS	 r\4S
 jrS rSS jrS rS rSrg)r   i  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           	         SnU(       al  US   [         L aN  US   U l        [        R                  X R                  R	                  5        VVs/ s H  u  pEXT4PM
     snn5        g US   [
        L a  USS  Sp1[        R                  " U /UQ70 UD6  U R                  [         U 5      U l        [        U 5      [        U R                  5      :X  a  g U(       dY  [        R                  U 5        [        R                  X R                  R	                  5        VVs/ s H  u  pEXT4PM
     snn5        g 0 nU R	                  5        H&  u  pEUR                  U/ 5      R                  U5        M(     [        UR	                  5        VVs/ s H  u  pW[        U5      S:  d  M  XW4PM     snn5      n[        SU-  5      es  snnf s  snnf s  snnf )NFr   r   TzFexpected unique values, got multiple keys for the following values: %r)_OTO_INV_MARKERr  r   r#   rw   _OTO_UNIQUE_MARKERr    r   r0   r&   r4   r7   
ValueError)	r'   akwraise_on_duper8   r9   val_multidictk_listdupess	            r   r#   OneToOne.__init__  s   t&Q4d8H$I8HaV8H$IJ1++#$QR5$=d%Q%"%>>/48t9DHH%JJtKK((..2BC2B$!v2BCD JJLDA$$Q+2215 ! #))+@+ '0a/26{Q "qk+@ A  57<= > 	>5 %J D@s   F8F>G
G
c                 "    U " [         /UQ70 UD6$ )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  )rb   r  r  s      r   uniqueOneToOne.unique0  s    $ %00R00r   c                    [        U5        X;   a"  [        R                  U R                  X   5        X R                  ;   a  U R                  U	 [        R	                  XU5        [        R	                  U R                  X!5        g r   )hashr   r   r  r}   r'   r   vals      r   r}   OneToOne.__setitem__D  s\    S	;TXXty1((?C(3,r   c                 r    [         R                  U R                  X   5        [         R                  X5        g r   )r   r   r  r'   r   s     r   r   OneToOne.__delitem__M  s&    49-#r   c                 l    [         R                  U 5        [         R                  U R                  5        g r   )r   r0   r  r^   s    r   r0   OneToOne.clearQ  s    

4

488r   c                 $    U R                  U 5      $ r   r   r^   s    r   r_   OneToOne.copyU  s    ~~d##r   c                     X;   a7  [         R                  U R                  X   5        [         R                  X5      $ U[        La  U$ [        5       er   )r   r   r  r   r	   rQ   r'   r   rM   s      r   r   OneToOne.popX  sA    ;TXXty188D&&("Njr   c                 v    [         R                  U 5      u  p[         R                  U R                  U5        X4$ r   )r   popitemr   r  r&  s      r   r4  OneToOne.popitem`  s-    <<%3'xr   Nc                     X;  a  X U'   X   $ r   r   r1  s      r   r4   OneToOne.setdefaulte  s    ?Iyr   c                    [        U[        5      (       a<  UR                  5        H'  n[        U5        [	        UR                  5       5      nM)     O,U H&  u  pS[        U5        [        U5        [	        U5      nM(     UR                  5        H  n[        U5        M     WR                  UR                  5       5        U H	  u  pSX0U'   M     g r   )rg   r   r@   r%  r   rw   rD   )r'   dict_or_iterabler  r'  	keys_valsr   s         r   r&   OneToOne.updatej  s    &--'..0S	 !1!7!7!9:	 1 -S	S	 !12	 - 99;CI $!HCI "r   c                 l    U R                   R                  n[        R                  U 5      nU< SU< S3$ N()r    r!   r   r   )r'   r   	dict_reprs      r   r   OneToOne.__repr__z  s*    ^^$$MM$'	y))r   r   )r!   r   r   r   r   	__slots__r#   r   r"  r}   r   r0   r_   r	   r   r4  r4   r&   r   r   r   r   r   r   r     sZ    6 I >D 1 1&-$$  ( 

 *r   r   c                       \ rS rSrSrSS jr\" 5       4S jrS rS r	S r
S	 rS
 rS rS rS rS rS rS rS rS rS rSrg)r   i  a  
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                     0 U l         [        U5      [        L a  U(       a  US   [        L a  US   U l        g U R                  [        U 45      U l        U(       a  U R                  U5        g )Nr   r   )datar   tuple_PAIRINGr  r    r&   )r'   rw   s     r   r#   ManyToMany.__init__  s[    	;%EeAh(.BQxDH
 	 ~~x&67DHE"r   c                 0     X   $ ! [          a    Us $ f = fr   )rQ   r1  s      r   rK   ManyToMany.get  s#    	9 	N	s    c                 2    [        U R                  U   5      $ r   )	frozensetrF  r*  s     r   rP   ManyToMany.__getitem__  s    3((r   c                     [        U5      nX;   a=  U R                  U   U-
  nX R                  U   -  nU H  nU R                  X5        M     U H  nU R                  X5        M     g r   )rj   rF  removerA   )r'   r   r   	to_remover'  s        r   r}   ManyToMany.__setitem__  s^    4y;		#-IIIcN"D C% !CHHS r   c                    U R                   R                  U5       Hb  nU R                  R                   U   R                  U5        U R                  R                   U   (       a  MK  U R                  R                   U	 Md     g r   )rF  r   r  rP  r&  s      r   r   ManyToMany.__delitem__  sW    99==%CHHMM#%%c*88==%%HHMM#& &r   c                 $   [        U5      [        U 5      L Ga  UnUR                   H[  nX0R                  ;  a  UR                  U   U R                  U'   M0  U R                  U   R                  UR                  U   5        M]     UR                  R                   H  nX0R                  R                  ;  a2  UR                  R                  U   U R                  R                  U'   MN  U R                  R                  U   R                  UR                  R                  U   5        M     g[	        [        USS5      5      (       a,  UR                  5        H  nU R                  X1U   5        M     gU H  u  pEU R                  XE5        M     g)z-given an iterable of (key, val), add them allrc   N)r   rF  r&   r  rh   ri   rc   rA   )r'   iterabler   r8   r   r'  s         r   r&   ManyToMany.update  s(   >T$Z'EZZII%#(::a=DIIaLIIaL''

16	  
 YY^^HHMM)',yy~~a'8DHHMM!$HHMM!$++EIINN1,=>	 $ 	 gh566]]_QK( %
 	 %" %r   c                 P   XR                   ;  a  [        5       U R                   U'   U R                   U   R                  U5        X R                  R                   ;  a!  [        5       U R                  R                   U'   U R                  R                   U   R                  U5        g r   )rF  rj   rA   r  r&  s      r   rA   ManyToMany.add  sn    ii UDIIcN		#3hhmm#!$DHHMM#cs#r   c                 >   U R                   U   R                  U5        U R                   U   (       d  U R                   U	 U R                  R                   U   R                  U5        U R                  R                   U   (       d  U R                  R                   U	 g g r   )rF  rP  r  r&  s      r   rP  ManyToMany.remove  sn    		#c"yy~		#c!!#&xx}}S!c" "r   c                     XR                   ;  a  gU R                   R                  U5      =U R                   U'   nU H>  nU R                  R                   U   nUR                  U5        UR	                  U5        M@     g)z$
replace instances of key by newkey
N)rF  r   r  rP  rA   )r'   r   newkeyfwdsetr'  revsets         r   replaceManyToMany.replace  se     ii%)YY]]3%77		&FCXX]]3'FMM#JJv r   c              #   h   #    U R                    H  nU R                   U    H  nX4v   M
     M      g 7fr   rF  r&  s      r   r]   ManyToMany.iteritems  s,     99Cyy~h & s   02c                 6    U R                   R                  5       $ r   )rF  rc   r^   s    r   rc   ManyToMany.keys  s    yy~~r   c                     XR                   ;   $ r   rc  r*  s     r   rW   ManyToMany.__contains__  s    iir   c                 6    U R                   R                  5       $ r   )rF  r   r^   s    r   r   ManyToMany.__iter__  s    yy!!##r   c                 6    U R                   R                  5       $ r   )rF  __len__r^   s    r   rl  ManyToMany.__len__  s    yy  ""r   c                 p    [        U 5      [        U5      :H  =(       a    U R                  UR                  :H  $ r   )r   rF  r   s     r   r   ManyToMany.__eq__  s'    DzT%[(DTYY%**-DDr   c                 p    U R                   R                  nU< S[        U R                  5       5      < S3$ r=  )r    r!   r   r]   r'   r   s     r   r   ManyToMany.__repr__  s(    ^^$$tDNN$4566r   )rF  r  r   )r!   r   r   r   r   r#   rM  rK   rP   r}   r   r&   rA   rP  r`  r]   rc   rW   r   rl  r   r   r   r   r   r   r   r     s_      ){ )',$#

  $#E7r   r   c                     Uc  U R                  5       nUc  / n[        U5      [        U5      -
  n[        U 5      " U R                  5        VVs/ s H  u  pEXC;   d  M  XE4PM     snn5      $ s  snnf )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}

)rc   rj   r   rw   )dkeepdroprc   r8   r9   s         r   r   r     sa    , |vvx|t9s4y D7qwwy>ytqAIFQFy>??>s   A,
A,
c                       \ rS rSrSrg)FrozenHashErrori  r   N)r!   r   r   r   r   r   r   r   rx  rx    s    r   rx  c                   v    \ rS rSrSrSrS r\SS j5       rS r	S r
S	 rS
 rS r\=r=r=rr\=r=r=rrCSrg)r   i   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                 ^    [        U 5      nUR                  " U0 UD6  [        U 5      " U5      $ )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  rF  s       r   updatedFrozenDict.updated/  s-    
 DzQ"Dz$r   Nc                 8    U " [         R                  X5      5      $ r   )r   rd   )rb   rc   values      r   rd   FrozenDict.fromkeys8  s     4==-..r   c                 h    U R                   R                  nU< S[        R                  U 5      < S3$ r=  r@  rq  s     r   r   FrozenDict.__repr__=  s%    ^^$$t}}T233r   c                 0    [        U 5      [        U 5      44$ r   )r   r   )r'   protocols     r   __reduce_ex__FrozenDict.__reduce_ex__A  s    DzDJ=((r   c                     U R                   nUR                  [        L a  UeU$ ! [         aU     [        [        U R	                  5       5      5      =ol          NL! [
         a  n[        U5      =ol          S nA NmS nAff = ff = fr   )rz  r.   r%  rM  rw   	Exceptionrx  r    )r'   r   es      r   __hash__FrozenDict.__hash__D  sy    	6**C ==O+I
  	66#'	$**,(?#@@j 6#21#55jj6	6s,   % 
B(A
B $A;5B;B  Bc                     U $ r   r   r^   s    r   __copy__FrozenDict.__copy__R  s    r   c                 F    [        SU R                  R                  -  5      e)z5raises a TypeError, because FrozenDicts are immutablez%s object is immutable)r   r    r!   )r'   r  r  s      r   _raise_frozen_typeerror"FrozenDict._raise_frozen_typeerrorV  s    04>>3J3JJKKr   r   )r!   r   r   r   r   rC  r|  r   rd   r   r  r  r  r  __ior__r}   r   r&   r4   r   r4  r0   r   r   r   r   r   r      so     I  / /4)L 4KJGJkJK&)@@J@@wr   r   r   )&r   collections.abcr   r   r   ImportErrorcollections	itertoolsr   r   	typeutilsr   r	   objectranger5   r6   r   r   r  r  __all__profile	NameErrorr   r   r   r   r   r  r  r   rH  r   r   r   rx  r   r   r   r   <module>r     s7  B%N<?? 6&'j1H
 (-Qx $dCu f
\t \@ 	_/ _D (X M*t M*b 8u7 u7p@@	i 	=  = m  <;;<  656  xH  GsD   
B B3 C C B0/B03CCCC	C$#C$