
    Vi                        S r SSKrSSKrSSKrSSKrSSKrSSKr SSKJrJ	r	J
r
JrJr   SSKJr  \" S5      r\" S5      r SSKJr  SSKJr  S	rS rS r S r!S9S jr"S9S jr#S:S jr$S:S jr%S:S jr&S:S jr'S:S jr(S:S jr)S:S jr*S r+S r,S r-S r.S r/S;S jr0S;S jr1S<S jr2S<S jr3\4SS4S  jr5\44S! jr6S:S" jr7S:S# jr8S=S$ jr9S9S% jr:S9S& jr;S' r<S( r=\4S) jr>S* r?\?r@S+ rAS, rB\?\A\B4S- jrC " S. S/\D\E\F5      rG\4S0 jrHS1 S	4S2 jrI " S3 S4\5      rJ " S5 S6\J5      rK\J" 5       rL\K" 5       rMS>S7 jrNS=S8 jrOg! \ a    SSKJrJ	r	J
r
JrJr   GN&f = f! \ a    \" 5       r\" 5       r GN*f = f! \ a    S
r\\4r\r\\srr GN5f = f)?a  :mod:`itertools` is full of great examples of Python generator
usage. However, there are still some critical gaps. ``iterutils``
fills many of those gaps with featureful, tested, and Pythonic
solutions.

Many of the functions below have two versions, one which
returns an iterator (denoted by the ``*_iter`` naming pattern), and a
shorter-named convenience form that returns a list. Some of the
following are based on examples in itertools docs.
    N)MappingSequenceSet	ItemsViewIterable)make_sentinel_UNSET_REMAP_EXIT)filter)izipFTc                 <     [        U 5        g! [         a     gf = f)zSimilar in nature to :func:`callable`, ``is_iterable`` returns
``True`` if an object is `iterable`_, ``False`` if not.

>>> is_iterable([])
True
>>> is_iterable(object())
False

.. _iterable: https://docs.python.org/2/glossary.html#term-iterable
FT)iter	TypeErrorobjs    d/home/james-whalen/.local/share/pipx/venvs/semgrep/lib/python3.13/site-packages/boltons/iterutils.pyis_iterabler   M   s'    S	   s    
c                 P    [        U 5      (       + =(       d    [        U [        5      $ )aN  A near-mirror of :func:`is_iterable`. Returns ``False`` if an
object is an iterable container type. Strings are considered
scalar as well, because strings are more often treated as whole
values as opposed to iterables of 1-character substrings.

>>> is_scalar(object())
True
>>> is_scalar(range(10))
False
>>> is_scalar('hello')
True
r   
isinstance
basestringr   s    r   	is_scalarr   _   s     3>:c:#>>    c                 P    [        U 5      =(       a    [        U [        5      (       + $ )zThe opposite of :func:`is_scalar`.  Returns ``True`` if an object
is an iterable other than a string.

>>> is_collection(object())
False
>>> is_collection(range(10))
True
>>> is_collection('hello')
False
r   r   s    r   is_collectionr   o   s     s?JsJ$? ??r   c                 ,    [        [        XU5      5      $ )a  Splits an iterable based on a separator. Like :meth:`str.split`,
but for all iterables. Returns a list of lists.

>>> split(['hi', 'hello', None, None, 'sup', None, 'soap', None])
[['hi', 'hello'], ['sup'], ['soap']]

See :func:`split_iter` docs for more info.
)list
split_iter)srcsepmaxsplits      r   splitr"   }   s     
3X.//r   c              #     ^#    [        U 5      (       d  [        S5      eUb  [        U5      nUS:X  a  U /v   g[        T5      (       a  TnO([	        T5      (       d  [        T5      mU4S jnOU4S jn/ nSnU  HE  nUb  XR:  a  S nU" U5      (       a  Tc	  U(       d  M'  US-  nUv   / nM4  UR                  U5        MG     U(       d  Tb  Uv   g7f)aD  Splits an iterable based on a separator, *sep*, a max of
*maxsplit* times (no max by default). *sep* can be:

  * a single value
  * an iterable of separators
  * a single-argument callable that returns True when a separator is
    encountered

``split_iter()`` yields lists of non-separator values. A separator will
never appear in the output.

>>> list(split_iter(['hi', 'hello', None, None, 'sup', None, 'soap', None]))
[['hi', 'hello'], ['sup'], ['soap']]

Note that ``split_iter`` is based on :func:`str.split`, so if
*sep* is ``None``, ``split()`` **groups** separators. If empty lists
are desired between two contiguous ``None`` values, simply use
``sep=[None]``:

>>> list(split_iter(['hi', 'hello', None, None, 'sup', None]))
[['hi', 'hello'], ['sup']]
>>> list(split_iter(['hi', 'hello', None, None, 'sup', None], sep=[None]))
[['hi', 'hello'], [], ['sup'], []]

Using a callable separator:

>>> falsy_sep = lambda x: not x
>>> list(split_iter(['hi', 'hello', None, '', 'sup', False], falsy_sep))
[['hi', 'hello'], [], ['sup'], []]

See :func:`split` for a list-returning version.

expected an iterableNr   c                    > U T;   $ N xr    s    r   <lambda>split_iter.<locals>.<lambda>   	    Q#Xr   c                    > U T:H  $ r&   r'   r(   s    r   r*   r+      r,   r   c                     gNFr'   r)   s    r   r*   r+      s    r      )r   r   intcallabler   	frozensetappend)r   r    r!   sep_func	cur_groupsplit_countss    `     r   r   r      s     D s.//x=q=%K}}s^^n%%IKK$;&HA;;{9 1KOIQ  CO
s   CCc                 *    [        [        X5      5      $ )zStrips values from the beginning of an iterable. Stripped items will
match the value of the argument strip_value. Functionality is analigous
to that of the method str.lstrip. Returns a list.

>>> lstrip(['Foo', 'Bar', 'Bam'], 'Foo')
['Bar', 'Bam']

)r   lstrip_iteriterablestrip_values     r   lstripr?      s     H233r   c              #   d   #    [        U 5      nU H  nX1:w  d  M
  Uv     O   U H  nUv   M	     g7f)a	  Strips values from the beginning of an iterable. Stripped items will
match the value of the argument strip_value. Functionality is analigous
to that of the method str.lstrip. Returns a generator.

>>> list(lstrip_iter(['Foo', 'Bar', 'Bam'], 'Foo'))
['Bar', 'Bam']

N)r   )r=   r>   iteratoris       r   r;   r;      s9      H~HG   s   00c                 *    [        [        X5      5      $ )zStrips values from the end of an iterable. Stripped items will
match the value of the argument strip_value. Functionality is analigous
to that of the method str.rstrip. Returns a list.

>>> rstrip(['Foo', 'Bar', 'Bam'], 'Bam')
['Foo', 'Bar']

)r   rstrip_iterr<   s     r   rstriprE      s     H122r   c              #      #    [        U 5      nU Hb  nX1:X  aV  [        5       nUR                  U5        SnU H  nX1:X  a  UR                  U5        M  Sn  O   U(       d    gU H  nUv   M	     Uv   Md     g7f)a  Strips values from the end of an iterable. Stripped items will
match the value of the argument strip_value. Functionality is analigous
to that of the method str.rstrip. Returns a generator.

>>> list(rstrip_iter(['Foo', 'Bar', 'Bam'], 'Bam'))
['Foo', 'Bar']

FTN)r   r   r5   )r=   r>   rA   rB   cachebrokents          r   rD   rD      sv      H~HFELLOF#LLO!F    s   A5A7c                 *    [        [        X5      5      $ )a  Strips values from the beginning and end of an iterable. Stripped items
will match the value of the argument strip_value. Functionality is
analigous to that of the method str.strip. Returns a list.

>>> strip(['Fu', 'Foo', 'Bar', 'Bam', 'Fu'], 'Fu')
['Foo', 'Bar', 'Bam']

)r   
strip_iterr<   s     r   striprL     s     
8011r   c                 ,    [        [        X5      U5      $ )a!  Strips values from the beginning and end of an iterable. Stripped items
will match the value of the argument strip_value. Functionality is
analigous to that of the method str.strip. Returns a generator.

>>> list(strip_iter(['Fu', 'Foo', 'Bar', 'Bam', 'Fu'], 'Fu'))
['Foo', 'Bar', 'Bam']

)rD   r;   r<   s     r   rK   rK   #  s     {88EEr   c                 t    [        X40 UD6nUc  [        U5      $ [        [        R                  " XB5      5      $ )a0  Returns a list of *count* chunks, each with *size* elements,
generated from iterable *src*. If *src* is not evenly divisible by
*size*, the final chunk will have fewer than *size* elements.
Provide the *fill* keyword argument to provide a pad value and
enable padding, otherwise no padding will take place.

>>> chunked(range(10), 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
>>> chunked(range(10), 3, fill=None)
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]]
>>> chunked(range(10), 3, count=2)
[[0, 1, 2], [3, 4, 5]]

See :func:`chunked_iter` for more info.
)chunked_iterr   	itertoolsislice)r   sizecountkw
chunk_iters        r   chunkedrV   /  s9      c.2.J}JI$$Z788r   c              +   ~  #    [        U 5      (       d  [        S5      e[        U5      nUS::  a  [        S5      eSn UR	                  S5      nU(       a  [        SUR                  5       -  5      eU (       d  gS	 n[        U [        5      (       a7  [        U 5      " 5       4S
 jn[        (       a  [        U [        5      (       a  S n[        U 5      n [        [        R                  " Xa5      5      nU(       d   g[!        U5      nX:  a  U(       a
  U/X-
  -  XxS& U" U5      v   MU  ! [
         a    SnSn Nf = f7f)a  Generates *size*-sized chunks from *src* iterable. Unless the
optional *fill* keyword argument is provided, iterables not evenly
divisible by *size* will have a final chunk that is smaller than
*size*.

>>> list(chunked_iter(range(10), 3))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
>>> list(chunked_iter(range(10), 3, fill=None))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, None, None]]

Note that ``fill=None`` in fact uses ``None`` as the fill value.
r$   r   z&expected a positive integer chunk sizeTfillFNz$got unexpected keyword arguments: %rc                     U $ r&   r'   chks    r   r*   chunked_iter.<locals>.<lambda>c  s    cr   c                 $    UR                  U 5      $ r&   )join)r[   _seps     r   r*   r\   e  s    DIIcNr   c                     [        U 5      $ r&   )bytesrZ   s    r   r*   r\   g  s    eCjr   )r   r   r2   
ValueErrorpopKeyErrorkeysr   r   type_IS_PY3ra   r   r   rP   rQ   len)	r   rR   rT   do_fillfill_valpostprocesssrc_iter	cur_chunklcs	            r   rO   rO   F  s#     s.//t9DqyABBG66&> 
?"'')KLL!K#z""'+Cy{B7z#u--0KCyH
))(9:	
 	 ^9&Z495IcN)$$   s)   :D=D) CD=)D:7D=9D::D=c                     [        U S5      $ )a3  Convenience function for calling :func:`windowed` on *src*, with
*size* set to 2.

>>> pairwise(range(5))
[(0, 1), (1, 2), (2, 3), (3, 4)]
>>> pairwise([])
[]

The number of pairs is always one less than the number of elements
in the iterable passed in, except on empty inputs, which returns
an empty list.
   )windowedr   s    r   pairwisers   t  s     Cr   c                     [        U S5      $ )a8  Convenience function for calling :func:`windowed_iter` on *src*,
with *size* set to 2.

>>> list(pairwise_iter(range(5)))
[(0, 1), (1, 2), (2, 3), (3, 4)]
>>> list(pairwise_iter([]))
[]

The number of pairs is always one less than the number of elements
in the iterable passed in, or zero, when *src* is empty.

rp   )windowed_iterrr   s    r   pairwise_iterrv     s     a  r   c                 *    [        [        X5      5      $ )zReturns tuples with exactly length *size*. If the iterable is
too short to make a window of length *size*, no tuples are
returned. See :func:`windowed_iter` for more.
)r   ru   )r   rR   s     r   rq   rq     s    
 c())r   c                     [         R                  " X5      n [        U5       H"  u  p4[        U5       H  n[	        U5        M     M$     [        U6 $ ! [
         a    [        / 5      s $ f = f)aD  Returns tuples with length *size* which represent a sliding
window over iterable *src*.

>>> list(windowed_iter(range(7), 3))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]

If the iterable is too short to make a window of length *size*,
then no window tuples are returned.

>>> list(windowed_iter(range(3), 5))
[]
)rP   tee	enumeratexrangenextStopIterationr   )r   rR   teesrB   rI   _s         r   ru   ru     sb     ==#DdODAAYQ  $
 ;  Bxs   1A A)(A)c              #      #    U(       d  [        S5      eUc  SU S-  pO	US-  U S-  pUnX0:  a  Uv   X2-  nX0:  a  M  gg7f)zSame as :func:`frange`, but generator-based instead of returning a
list.

>>> tuple(xfrange(1, 3, step=0.75))
(1.0, 1.75, 2.5)

See :func:`frange` for more details.
step must be non-zeroN              ?)rb   )stopstartstepcurs       r   xfranger     sT      011}4#:t ck4#:e
C
*	 *s
   :A A c                     U(       d  [        S5      eUc  SU S-  pO	US-  U S-  p[        [        R                  " X-
  U-  5      5      nS/U-  nU(       d  U$ XS'   [	        SU5       H  nXES-
     U-   XE'   M     U$ )a  A :func:`range` clone for float-based ranges.

>>> frange(5)
[0.0, 1.0, 2.0, 3.0, 4.0]
>>> frange(6, step=1.25)
[0.0, 1.25, 2.5, 3.75, 5.0]
>>> frange(100.5, 101.5, 0.25)
[100.5, 100.75, 101.0, 101.25]
>>> frange(5, 0)
[]
>>> frange(5, 0, step=-1.25)
[5.0, 3.75, 2.5, 1.25]
r   Nr   r   r   r1   )rb   r2   mathceilr{   )r   r   r   rS   retrB   s         r   franger     s     011}4#:t ck4#:e		4<4/01E&5.C
FAuUd" Jr   c           
      L    US:X  a  [        S5      e[        [        XUX4S95      $ )am  Returns a list of geometrically-increasing floating-point numbers,
suitable for usage with `exponential backoff`_. Exactly like
:func:`backoff_iter`, but without the ``'repeat'`` option for
*count*. See :func:`backoff_iter` for more details.

.. _exponential backoff: https://en.wikipedia.org/wiki/Exponential_backoff

>>> backoff(1, 10)
[1.0, 2.0, 4.0, 8.0, 10.0]
repeatz/'repeat' supported in backoff_iter, not backoff)rS   factorjitter)rb   r   backoff_iter)r   r   rS   r   r   s        r   backoffr     s3     JKKU$*; < <r   c              #     #    [        U 5      n [        U5      n[        U5      nU S:  a  [        SU -  5      eUS:  a  [        SU-  5      eUS:X  a  [        S5      eX:  a  [        SU-  5      eUcI  U (       a  U OSnS[        R                  " [        R                  " X-  U5      5      -   nU (       a  UOUS-   nUS	:w  a  US
:  a  [        SU-  5      eU(       a(  [        U5      nSUs=::  a  S::  d  O  [        SU-  5      eU S
pvUS	:X  d  Xr:  a_  U(       d  UnO$U(       a  XfU-  [
        R
                  " 5       -  -
  nWv   US-  nUS
:X  a  SnO	Xa:  a  Xc-  nXa:  a  UnUS	:X  a  MX  Xr:  a  M_  g7f)a  Generates a sequence of geometrically-increasing floats, suitable
for usage with `exponential backoff`_. Starts with *start*,
increasing by *factor* until *stop* is reached, optionally
stopping iteration once *count* numbers are yielded. *factor*
defaults to 2. In general retrying with properly-configured
backoff creates a better-behaved component for a larger service
ecosystem.

.. _exponential backoff: https://en.wikipedia.org/wiki/Exponential_backoff

>>> list(backoff_iter(1.0, 10.0, count=5))
[1.0, 2.0, 4.0, 8.0, 10.0]
>>> list(backoff_iter(1.0, 10.0, count=8))
[1.0, 2.0, 4.0, 8.0, 10.0, 10.0, 10.0, 10.0]
>>> list(backoff_iter(0.25, 100.0, factor=10))
[0.25, 2.5, 25.0, 100.0]

A simplified usage example:

.. code-block:: python

  for timeout in backoff_iter(0.25, 5.0):
      try:
          res = network_call()
          break
      except Exception as e:
          log(e)
          time.sleep(timeout)

An enhancement for large-scale systems would be to add variation,
or *jitter*, to timeout values. This is done to avoid a thundering
herd on the receiving end of the network call.

Finally, for *count*, the special value ``'repeat'`` can be passed to
continue yielding indefinitely.

Args:

    start (float): Positive number for baseline.
    stop (float): Positive number for maximum.
    count (int): Number of steps before stopping
        iteration. Defaults to the number of steps between *start* and
        *stop*. Pass the string, `'repeat'`, to continue iteration
        indefinitely.
    factor (float): Rate of exponential increase. Defaults to `2.0`,
        e.g., `[1, 2, 4, 8, 16]`.
    jitter (float): A factor between `-1.0` and `1.0`, used to
        uniformly randomize and thus spread out timeouts in a distributed
        system, avoiding rhythm effects. Positive values use the base
        backoff curve as a maximum, negative values use the curve as a
        minimum. Set to 1.0 or `True` for a jitter approximating
        Ethernet's time-tested backoff solution. Defaults to `False`.

r   zexpected start >= 0, not %rr   zexpected factor >= 1.0, not %rzexpected stop >= 0zexpected stop >= start, not %rNr1   r   r   z*count must be positive or "repeat", not %rg      z%expected jitter -1 <= j <= 1, not: %r)floatrb   r   r   lograndom)	r   r   rS   r   r   denomr   rB   cur_rets	            r   r   r     sx    n %LE;D6]Fs{6>??|9FBCCs{-..|9D@AA}ADIIdhhtz6:;;EAIUQYEMNNv%#%DvMNNA
8
qyG6\FMMO;<G	Q!8CZMC:C 8
qy s   E'E3+E32E3c                   ^^ [        U 5      (       d  [        S5      e[        T[        5      (       a/  [	        T5      [	        U 5      :w  a  [        S5      e[        TU 5      n [        T[        5      (       a  U4S jnO7[        T5      (       a  TnO$[        T[        5      (       a  S nO[        S5      eUc  S n[        U5      (       d  [        S5      e[        T[        5      (       a  UmU4S jn0 nU  HD  nU" U5      nUb  U" U5      (       d  M  UR                  U/ 5      R                  U" U5      5        MF     U$ )	a  Group values in the *src* iterable by the value returned by *key*.

>>> bucketize(range(5))
{False: [0], True: [1, 2, 3, 4]}
>>> is_odd = lambda x: x % 2 == 1
>>> bucketize(range(5), is_odd)
{False: [0, 2, 4], True: [1, 3]}

*key* is :class:`bool` by default, but can either be a callable or a string or a list
if it is a string, it is the name of the attribute on which to bucketize objects.

>>> bucketize([1+1j, 2+2j, 1, 2], key='real')
{1.0: [(1+1j), 1], 2.0: [(2+2j), 2]}

if *key* is a list, it contains the buckets where to put each object

>>> bucketize([1,2,365,4,98],key=[0,1,2,0,2])
{0: [1, 4], 1: [2], 2: [365, 98]}


Value lists are not deduplicated:

>>> bucketize([None, None, None, 'hello'])
{False: [None, None, None], True: ['hello']}

Bucketize into more than 3 groups

>>> bucketize(range(10), lambda x: x % 3)
{0: [0, 3, 6, 9], 1: [1, 4, 7], 2: [2, 5, 8]}

``bucketize`` has a couple of advanced options useful in certain
cases.  *value_transform* can be used to modify values as they are
added to buckets, and *key_filter* will allow excluding certain
buckets from being collected.

>>> bucketize(range(5), value_transform=lambda x: x*x)
{False: [0], True: [1, 4, 9, 16]}

>>> bucketize(range(10), key=lambda x: x % 3, key_filter=lambda k: k % 3 != 1)
{0: [0, 3, 6, 9], 2: [2, 5, 8]}

Note in some of these examples there were at most two keys, ``True`` and
``False``, and each key present has a list with at least one
item. See :func:`partition` for a version specialized for binary
use cases.

r$   z&key and src have to be the same lengthc                    > [        U TU 5      $ r&   getattrr)   keys    r   r*   bucketize.<locals>.<lambda>      WQQ/r   c                     U S   $ )Nr   r'   r0   s    r   r*   r     s    QqTr   z1expected key to be callable or a string or a listc                     U $ r&   r'   r0   s    r   r*   r     s    Ar   z*expected callable value transform functionc                    > T" U S   5      $ )Nr1   r'   )r)   fs    r   r*   r     s    !AaD'r   )r   r   r   r   rh   rb   zipr   r3   
setdefaultr5   )	r   r   value_transform
key_filterkey_funcr   val
key_of_valr   s	    `      @r   	bucketizer   X  s   ` s.//	C		s8s3xEFF#sm#z""/	#	C		!KLL%O$$DEE#t)
Cc]
J!7!7NN:r*11/#2FG  Jr   c                 `    [        X5      nUR                  S/ 5      UR                  S/ 5      4$ )a  No relation to :meth:`str.partition`, ``partition`` is like
:func:`bucketize`, but for added convenience returns a tuple of
``(truthy_values, falsy_values)``.

>>> nonempty, empty = partition(['', '', 'hi', '', 'bye'])
>>> nonempty
['hi', 'bye']

*key* defaults to :class:`bool`, but can be carefully overridden to
use either a function that returns either ``True`` or ``False`` or
a string name of the attribute on which to partition objects.

>>> import string
>>> is_digit = lambda x: x in string.digits
>>> decimal_digits, hexletters = partition(string.hexdigits, is_digit)
>>> ''.join(decimal_digits), ''.join(hexletters)
('0123456789', 'abcdefABCDEF')
TF)r   get)r   r   
bucketizeds      r   	partitionr     s/    & 3$J>>$#Z^^E2%>>>r   c                 *    [        [        X5      5      $ )a
  ``unique()`` returns a list of unique values, as determined by
*key*, in the order they first appeared in the input iterable,
*src*.

>>> ones_n_zeros = '11010110001010010101010'
>>> ''.join(unique(ones_n_zeros))
'10'

See :func:`unique_iter` docs for more details.
)r   unique_iter)r   r   s     r   uniquer     s     C%&&r   c              #   R  ^#    [        U 5      (       d  [        S[        U 5      -  5      eTc  S nO=[        T5      (       a  TnO*[	        T[
        5      (       a  U4S jnO[        ST-  5      e[        5       nU  H'  nU" U5      nXS;  d  M  UR                  U5        Uv   M)     g7f)a'  Yield unique elements from the iterable, *src*, based on *key*,
in the order in which they first appeared in *src*.

>>> repetitious = [1, 2, 3] * 10
>>> list(unique_iter(repetitious))
[1, 2, 3]

By default, *key* is the object itself, but *key* can either be a
callable or, for convenience, a string name of the attribute on
which to uniqueify objects, falling back on identity when the
attribute is not present.

>>> pleasantries = ['hi', 'hello', 'ok', 'bye', 'yes']
>>> list(unique_iter(pleasantries, key=lambda x: len(x)))
['hi', 'hello', 'bye']
zexpected an iterable, not %rNc                     U $ r&   r'   r0   s    r   r*   unique_iter.<locals>.<lambda>  s    Qr   c                    > [        U TU 5      $ r&   r   r   s    r   r*   r     r   r   +"key" expected a string or callable, not %r)r   r   rf   r3   r   r   setadd)r   r   r   seenrB   ks    `    r   r   r     s     " s6cBCC
{	#	C	$	$/EKLL5DQK=HHQKG	 
 s   BB'B'c                   ^ Tc  O=[        T5      (       a  TnO*[        T[        5      (       a  U4S jnO[        ST-  5      e0 n/ n0 nU  H[  nT(       a  W" U5      OUnX;  a  XtU'   M  X;   a  U(       a  Xh   R	                  U5        M@  MB  UR	                  U5        XH   U/Xh'   M]     U(       d  U Vs/ s H
  oU   S   PM     n	nU	$ U Vs/ s H  oU   PM	     n	nU	$ s  snf s  snf )a  The complement of :func:`unique()`.

By default returns non-unique/duplicate values as a list of the
*first* redundant value in *src*. Pass ``groups=True`` to get
groups of all values with redundancies, ordered by position of the
first redundant value. This is useful in conjunction with some
normalizing *key* function.

>>> redundant([1, 2, 3, 4])
[]
>>> redundant([1, 2, 3, 2, 3, 3, 4])
[2, 3]
>>> redundant([1, 2, 3, 2, 3, 3, 4], groups=True)
[[2, 2], [3, 3, 3]]

An example using a *key* function to do case-insensitive
redundancy detection.

>>> redundant(['hi', 'Hi', 'HI', 'hello'], key=str.lower)
['Hi']
>>> redundant(['hi', 'Hi', 'HI', 'hello'], groups=True, key=str.lower)
[['hi', 'Hi', 'HI']]

*key* should also be used when the values in *src* are not hashable.

.. note::

   This output of this function is designed for reporting
   duplicates in contexts when a unique input is desired. Due to
   the grouped return type, there is no streaming equivalent of
   this function for the time being.

c                    > [        U TU 5      $ r&   r   r   s    r   r*   redundant.<locals>.<lambda>  r   r   r   r1   )r3   r   r   r   r5   )
r   r   groupsr   r   redundant_orderredundant_groupsrB   r   r   s
    `        r   	redundantr     s    D {	#	C	$	$/EKLLDOHQKA=G$$'..q1   &&q)'+wl #  />?!"1%? J -<<Oq"O<J @<s   5C C%c                     [        [        R                  " [        X 5      S5      5      n[	        U5      S:X  a  US   $ U$ )u  Along the same lines as builtins, :func:`all` and :func:`any`, and
similar to :func:`first`, ``one()`` returns the single object in
the given iterable *src* that evaluates to ``True``, as determined
by callable *key*. If unset, *key* defaults to :class:`bool`. If
no such objects are found, *default* is returned. If *default* is
not passed, ``None`` is returned.

If *src* has more than one object that evaluates to ``True``, or
if there is no object that fulfills such condition, return
*default*. It's like an `XOR`_ over an iterable.

>>> one((True, False, False))
True
>>> one((True, False, True))
>>> one((0, 0, 'a'))
'a'
>>> one((0, False, None))
>>> one((True, True), default=False)
False
>>> bool(one(('', 1)))
True
>>> one((10, 20, 30, 42), key=lambda i: i > 40)
42

See `Martín Gaitán's original repo`_ for further use cases.

.. _Martín Gaitán's original repo: https://github.com/mgaitan/one
.. _XOR: https://en.wikipedia.org/wiki/Exclusive_or

rp   r1   r   )r   rP   rQ   r   rh   )r   defaultr   oness       r   oner   0  s9    > 	  !1156D$i1n471'1r   c                 ,    [        [        X 5      U5      $ )a+  Return first element of *iterable* that evaluates to ``True``, else
return ``None`` or optional *default*. Similar to :func:`one`.

>>> first([0, False, None, [], (), 42])
42
>>> first([0, False, None, [], ()]) is None
True
>>> first([0, False, None, [], ()], default='ohai')
'ohai'
>>> import re
>>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
>>> m.group(1)
'bc'

The optional *key* argument specifies a one-argument predicate function
like that used for *filter()*.  The *key* argument, if supplied, should be
in keyword form. For example, finding the first even number in an iterable:

>>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
4

Contributed by Hynek Schlawack, author of `the original standalone module`_.

.. _the original standalone module: https://github.com/hynek/first
)r|   r   )r=   r   r   s      r   firstr   S  s    4 s%w//r   c              #      #    U  HI  n[        U[        5      (       a-  [        U[        5      (       d  [        U5       H  nUv   M	     ME  Uv   MK     g7f)z``flatten_iter()`` yields all the elements from *iterable* while
collapsing any nested iterables.

>>> nested = [[1, 2], [[3], [4, 5]]]
>>> list(flatten_iter(nested))
[1, 2, 3, 4, 5]
N)r   r   r   flatten_iter)r=   itemsubitems      r   r   r   p  sE      dH%%jz.J.J'- . J s   AAc                 *    [        [        U 5      5      $ )z``flatten()`` returns a collapsed list of all the elements from
*iterable* while collapsing any nested iterables.

>>> nested = [[1, 2], [[3], [4, 5]]]
>>> flatten(nested)
[1, 2, 3, 4, 5]
)r   r   )r=   s    r   flattenr     s     X&''r   c                 n   ^ [        U 5      nT[        L a  [        UT5      m[        U4S jU 5       5      $ )a  ``same()`` returns ``True`` when all values in *iterable* are
equal to one another, or optionally a reference value,
*ref*. Similar to :func:`all` and :func:`any` in that it evaluates
an iterable and returns a :class:`bool`. ``same()`` returns
``True`` for empty iterables.

>>> same([])
True
>>> same([1])
True
>>> same(['a', 'a', 'a'])
True
>>> same(range(20))
False
>>> same([[], []])
True
>>> same([[], []], ref='test')
False

c              3   ,   >#    U  H	  oT:H  v   M     g 7fr&   r'   ).0r   refs     r   	<genexpr>same.<locals>.<genexpr>  s     .XcczXs   )r   r	   r|   all)r=   r   rA   s    ` r   samer     s2    * H~H
f}8S!.X...r   c                     X4$ r&   r'   pathr   values      r   default_visitr     s
    :r   c                 \   [        U[        5      (       a  US4$ [        U[        5      (       a  UR                  5       [	        U5      4$ [        U[
        5      (       a  UR                  5       [        U5      4$ [        U[        5      (       a  UR                  5       [        U5      4$ US4$ r/   )r   r   r   	__class__r   r   rz   r   r   s      r   default_enterr     s    %$$e|	E7	#	# )E"222	E8	$	$ )E"222	E3		 )E"222 e|r   c                     Un[        U[        5      (       a  UR                  U5        U$ [        U[        5      (       a*  U VVs/ s H  u  pgUPM	     nnn UR	                  U5        U$ [        U[        5      (       a*  U VVs/ s H  u  pgUPM	     nnn UR                  U5        U$ [        S[        U5      -  5      es  snnf ! [
         a    UR                  U5      n U$ f = fs  snnf ! [
         a    UR                  U5      n U$ f = f)Nzunexpected iterable type: %r)
r   r   updater   extendAttributeErrorr   r   RuntimeErrorrf   )	r   r   
old_parent
new_parent	new_itemsr   rB   vvalss	            r   default_exitr     s    C*g&&)$ J 
J	)	)'(idai(	-d# J 
J	$	$'(idai(	-d#
 J 9D<LLMM )  	-&&t,C J	- )  	-&&t,C J		-s0   C C C(C. C%$C%.DDc                 B   [        U5      (       d  [        SU-  5      e[        U5      (       d  [        SU-  5      e[        U5      (       d  [        SU-  5      eUR                  SS5      nU(       a  [        SUR                  5       -  5      eS0 SU 4/pn/ n	U(       Ga+  UR                  5       u  p[	        U5      nU
[
        L a:  Uu  pn[	        U5      nU	R                  5       u  poU" XjXU5      nXU'   U	(       d  Mg  OX;   a  X|   nOxU" XjU5      n Uu  pUS
Lae  XU'   U	R                  U/ 45        XLa  Xj4-  nUR                  [
        XU445        U(       a#  UR                  [        [        U5      5      5        M  U[        L a  X4nO U" XjU5      nUS
L a  GM	  USL a  X4n U	S   S   R                  U5        U(       a  GM+  W$ ! [         a    [        S	U-  5      ef = f! [         a    U(       a  e Sn Nff = f! [         a    [        SU -  5      ef = f)a-  The remap ("recursive map") function is used to traverse and
transform nested structures. Lists, tuples, sets, and dictionaries
are just a few of the data structures nested into heterogenous
tree-like structures that are so common in programming.
Unfortunately, Python's built-in ways to manipulate collections
are almost all flat. List comprehensions may be fast and succinct,
but they do not recurse, making it tedious to apply quick changes
or complex transforms to real-world data.

remap goes where list comprehensions cannot.

Here's an example of removing all Nones from some data:

>>> from pprint import pprint
>>> reviews = {'Star Trek': {'TNG': 10, 'DS9': 8.5, 'ENT': None},
...            'Babylon 5': 6, 'Dr. Who': None}
>>> pprint(remap(reviews, lambda p, k, v: v is not None))
{'Babylon 5': 6, 'Star Trek': {'DS9': 8.5, 'TNG': 10}}

Notice how both Nones have been removed despite the nesting in the
dictionary. Not bad for a one-liner, and that's just the beginning.
See `this remap cookbook`_ for more delicious recipes.

.. _this remap cookbook: http://sedimental.org/remap.html

remap takes four main arguments: the object to traverse and three
optional callables which determine how the remapped object will be
created.

Args:

    root: The target object to traverse. By default, remap
        supports iterables like :class:`list`, :class:`tuple`,
        :class:`dict`, and :class:`set`, but any object traversable by
        *enter* will work.
    visit (callable): This function is called on every item in
        *root*. It must accept three positional arguments, *path*,
        *key*, and *value*. *path* is simply a tuple of parents'
        keys. *visit* should return the new key-value pair. It may
        also return ``True`` as shorthand to keep the old item
        unmodified, or ``False`` to drop the item from the new
        structure. *visit* is called after *enter*, on the new parent.

        The *visit* function is called for every item in root,
        including duplicate items. For traversable values, it is
        called on the new parent object, after all its children
        have been visited. The default visit behavior simply
        returns the key-value pair unmodified.
    enter (callable): This function controls which items in *root*
        are traversed. It accepts the same arguments as *visit*: the
        path, the key, and the value of the current item. It returns a
        pair of the blank new parent, and an iterator over the items
        which should be visited. If ``False`` is returned instead of
        an iterator, the value will not be traversed.

        The *enter* function is only called once per unique value. The
        default enter behavior support mappings, sequences, and
        sets. Strings and all other iterables will not be traversed.
    exit (callable): This function determines how to handle items
        once they have been visited. It gets the same three
        arguments as the other functions -- *path*, *key*, *value*
        -- plus two more: the blank new parent object returned
        from *enter*, and a list of the new items, as remapped by
        *visit*.

        Like *enter*, the *exit* function is only called once per
        unique value. The default exit behavior is to simply add
        all new items to the new parent, e.g., using
        :meth:`list.extend` and :meth:`dict.update` to add to the
        new parent. Immutable objects, such as a :class:`tuple` or
        :class:`namedtuple`, must be recreated from scratch, but
        use the same type as the new parent passed back from the
        *enter* function.
    reraise_visit (bool): A pragmatic convenience for the *visit*
        callable. When set to ``False``, remap ignores any errors
        raised by the *visit* callback. Items causing exceptions
        are kept. See examples for more details.

remap is designed to cover the majority of cases with just the
*visit* callable. While passing in multiple callables is very
empowering, remap is designed so very few cases should require
passing more than one function.

When passing *enter* and *exit*, it's common and easiest to build
on the default behavior. Simply add ``from boltons.iterutils import
default_enter`` (or ``default_exit``), and have your enter/exit
function call the default behavior before or after your custom
logic. See `this example`_.

Duplicate and self-referential objects (aka reference loops) are
automatically handled internally, `as shown here`_.

.. _this example: http://sedimental.org/remap.html#sort_all_lists
.. _as shown here: http://sedimental.org/remap.html#corner_cases

z visit expected callable, not: %rz enter expected callable, not: %rzexit expected callable, not: %rreraise_visitTz unexpected keyword arguments: %rr'   NzDenter should return a tuple of (new_parent, items_iterator), not: %rFr1   z!expected remappable root, not: %r)r3   r   rc   re   idr
   r5   r   reversedr   _orig_default_visit	Exception
IndexError)rootvisitenterexitkwargsr   r   registrystacknew_items_stackr   r   id_valuer   r   r   resvisited_items                     r   remapr     s^   H E??:UBCCE??:UBCCD>>9D@AAJJ5M:V[[]JKKdD\NEDO
YY[
e9+*/'CZ*~H-113ODJIFE!&X" #!&E5)CC(+%

 %%/"&&bz2$FNDkCU+CDELL$y/!:;''<L$$T6
 u$% #|	HB")),7c %h LG  C !<>A!B C CC(  $ #$  	H?$FGG	Hs*   G 	G+ ,H G(+HHHc                   *    \ rS rSrSrS rS rS rSrg)PathAccessErrori{  zAn amalgamation of KeyError, IndexError, and TypeError,
representing what can occur when looking up a path in a nested
object.
c                 (    Xl         X l        X0l        g r&   )excsegr   )selfr  r  r   s       r   __init__PathAccessError.__init__  s    	r   c                     U R                   R                  nU< SU R                  < SU R                  < SU R                  < S3$ )N(z, ))r   __name__r  r  r   )r  cns     r   __repr__PathAccessError.__repr__  s,    ^^$$#%txx499EEr   c                 Z    SU R                   < SU R                  < SU R                  < 3$ )Nzcould not access z from path z, got error: )r  r   r  r  s    r   __str__PathAccessError.__str__  s    88TYY2 	3r   )r  r   r  N)	r  
__module____qualname____firstlineno____doc__r  r  r  __static_attributes__r'   r   r   r  r  {  s    
F3r   r  c           	         [        U[        5      (       a  UR                  S5      nU n U H  n X4   nM
     U$ ! [        [        4 a  n[        XTU5      eSnAf[         av  n [        U5      nX4   n SnAMM  ! [        [        [        [        4 a>    [        U5      (       d!  [        S[        U5      R                  -  5      n[        XTU5      ef = fSnAff = f! [
         a    U[        L a  e Us $ f = f)a0  Retrieve a value from a nested object via a tuple representing the
lookup path.

>>> root = {'a': {'b': {'c': [[1], [2], [3]]}}}
>>> get_path(root, ('a', 'b', 'c', 2, 0))
3

The path format is intentionally consistent with that of
:func:`remap`.

One of get_path's chief aims is improved error messaging. EAFP is
great, but the error messages are not.

For instance, ``root['a']['b']['c'][2][1]`` gives back
``IndexError: list index out of range``

What went out of range where? get_path currently raises
``PathAccessError: could not access 2 from path ('a', 'b', 'c', 2,
1), got error: IndexError('list index out of range',)``, a
subclass of IndexError and KeyError.

You can also pass a default that covers the entire operation,
should the lookup fail at any level.

Args:
   root: The target nesting of dictionaries, lists, or other
      objects supporting ``__getitem__``.
   path (tuple): A list of strings and integers to be successively
      looked up within *root*.
   default: The value to be returned should any
      ``PathAccessError`` exceptions be raised.
.Nz%r object is not indexable)r   r   r"   rd   r   r  r   r2   rb   r   rf   r  r	   )r   r   r   r   r  r  s         r   get_pathr    s    B $
##zz#
CC:h ( J# j) 6%c55 
::c(C(C"Hj)D :&s++'(D*.s)*<*<)= >)#D99	:
:  fsP   C :C C
AC$A93C 9ACCCC C54C5c                     g)NTr'   )pr   r   s      r   r*   r*     s    r   c                 n   ^^^ / m[        T5      (       d  [        ST-  5      eUUU4S jn[        XS9  T$ )a  The :func:`research` function uses :func:`remap` to recurse over
any data nested in *root*, and find values which match a given
criterion, specified by the *query* callable.

Results are returned as a list of ``(path, value)`` pairs. The
paths are tuples in the same format accepted by
:func:`get_path`. This can be useful for comparing values nested
in two or more different structures.

Here's a simple example that finds all integers:

>>> root = {'a': {'b': 1, 'c': (2, 'd', 3)}, 'e': None}
>>> res = research(root, query=lambda p, k, v: isinstance(v, int))
>>> print(sorted(res))
[(('a', 'b'), 1), (('a', 'c', 0), 2), (('a', 'c', 2), 3)]

Note how *query* follows the same, familiar ``path, key, value``
signature as the ``visit`` and ``enter`` functions on
:func:`remap`, and returns a :class:`bool`.

Args:
   root: The target object to search. Supports the same types of
      objects as :func:`remap`, including :class:`list`,
      :class:`tuple`, :class:`dict`, and :class:`set`.
   query (callable): The function called on every object to
      determine whether to include it in the search results. The
      callable must accept three arguments, *path*, *key*, and
      *value*, commonly abbreviated *p*, *k*, and *v*, same as
      *enter* and *visit* from :func:`remap`.
   reraise (bool): Whether to reraise exceptions raised by *query*
      or to simply drop the result that caused the error.


With :func:`research` it's easy to inspect the details of a data
structure, like finding values that are at a certain depth (using
``len(p)``) and much more. If more advanced functionality is
needed, check out the code and make your own :func:`remap`
wrapper, and consider `submitting a patch`_!

.. _submitting a patch: https://github.com/mahmoud/boltons/pulls
z query expected callable, not: %rc                    >  T" XU5      (       a  TR                  X4-   U45        [        XU5      $ ! [         a    T(       a  e  N f = fr&   )r5   r   r   )r   r   r   queryreraiser   s      r   r   research.<locals>.enter  sU    	T&&

D6M512 T..  	 	s   $3 AA)r   )r3   r   r   )r   r  r   r   r   s    `` @r   researchr"    s9    T CE??:UBCC/ 
$Jr   c                   N    \ rS rSrSrS
S jrS rS r\(       a  S r	OS r	\	r
Srg	)
GUIDeratori  a  The GUIDerator is an iterator that yields a globally-unique
identifier (GUID) on every iteration. The GUIDs produced are
hexadecimal strings.

Testing shows it to be around 12x faster than the uuid module. By
default it is also more compact, partly due to its default 96-bit
(24-hexdigit) length. 96 bits of randomness means that there is a
1 in 2 ^ 32 chance of collision after 2 ^ 64 iterations. If more
or less uniqueness is desired, the *size* argument can be adjusted
accordingly.

Args:
    size (int): character length of the GUID, defaults to 24. Lengths
                between 20 and 36 are considered valid.

The GUIDerator has built-in fork protection that causes it to
detect a fork on next iteration and reseed accordingly.

c                     Xl         US:  d  US:  a  [        S5      eSS KnUR                  U l        [
        R                  " 5       U l        U R                  5         g )N   $   zexpected 20 < size <= 36r   )rR   rb   hashlibsha1_sha1rP   rS   reseed)r  rR   r(  s      r   r  GUIDerator.__init__!  sE    	"9r	788\\
__&
r   c           
      p   SS K n[        R                  " 5       U l        SR	                  [        U R                  5      UR                  5       =(       d    S[        [        R                  " 5       5      [        R                  " [        R                  " S5      S5      R                  S5      /5      U l        g )Nr   -s   <nohostname>   	hex_codecascii)socketosgetpidpidr^   strgethostnametimecodecsencodeurandomdecodesalt)r  r2  s     r   r+  GUIDerator.reseed*  sy    99;HHc$((m$002Eo!$))+.$mmBJJqM,799?	J K	 	r   c                     U $ r&   r'   r  s    r   __iter__GUIDerator.__iter__6  s    r   c                 8   [         R                  " 5       U R                  :w  a  U R                  5         U R                  [        [        U R                  5      5      -   R                  S5      nU R                  U5      R                  5       S U R                   nU$ )Nutf8)r3  r4  r5  r+  r=  r6  r|   rS   r:  r*  	hexdigestrR   )r  target_bytes	hash_texts      r   __next__GUIDerator.__next__:  sl    yy{dhh& IID,<(==EEfML

<0::<ZdiiHIr   c                    [         R                  " 5       U R                  :w  a  U R                  5         U R	                  U R
                  [        [        U R                  5      5      -   5      R                  5       S U R                   $ r&   )r3  r4  r5  r+  r*  r=  r6  r|   rS   rD  rR   r  s    r   rG  rH  A  s`    yy{dhh&::dii!$tzz"234 55>Y[$))M Mr   )r*  rS   r5  r=  rR   N)   )r  r  r  r  r  r  r+  r@  rg   rG  r|   r  r'   r   r   r$  r$    s-    &
 		M Dr   r$  c                   R   ^  \ rS rSrSr\(       a  U 4S jrOU 4S jrS r\rSr	U =r
$ )SequentialGUIDeratoriJ  aO  Much like the standard GUIDerator, the SequentialGUIDerator is an
iterator that yields a globally-unique identifier (GUID) on every
iteration. The GUIDs produced are hexadecimal strings.

The SequentialGUIDerator differs in that it picks a starting GUID
value and increments every iteration. This yields GUIDs which are
of course unique, but also ordered and lexicographically sortable.

The SequentialGUIDerator is around 50% faster than the normal
GUIDerator, making it almost 20x as fast as the built-in uuid
module. By default it is also more compact, partly due to its
96-bit (24-hexdigit) default length. 96 bits of randomness means that
there is a 1 in 2 ^ 32 chance of collision after 2 ^ 64
iterations. If more or less uniqueness is desired, the *size*
argument can be adjusted accordingly.

Args:
    size (int): character length of the GUID, defaults to 24.

Note that with SequentialGUIDerator there is a chance of GUIDs
growing larger than the size configured. The SequentialGUIDerator
has built-in fork protection that causes it to detect a fork on
next iteration and reseed accordingly.

c                 &  > [         [        U ]  5         U R                  U R                  R                  S5      5      R                  5       n[        US U R                   S5      U l	        U =R                  SU R                  S-  S-
  -  -  sl	        g )NrC     r1      rp   )
superrL  r+  r*  r=  r:  rD  r2   rR   r   r  	start_strr   s     r   r+  SequentialGUIDerator.reseedf  sp    &46

499#3#3F#;<FFHIYz		2B7DJJJ1$))a-1!456Jr   c                   > [         [        U ]  5         U R                  U R                  5      R                  5       n[        US U R                   S5      U l        U =R                  SU R                  S-  S-
  -  -  sl        g )NrN  r1   rO  rp   )	rP  rL  r+  r*  r=  rD  r2   rR   r   rQ  s     r   r+  rS  l  se    &46

499-779IYz		2B7DJJJ1$))a-1!456Jr   c                     [         R                  " 5       U R                  :w  a  U R                  5         S[	        U R
                  5      U R                  -   -  $ )Nz%x)r3  r4  r5  r+  r|   rS   r   r  s    r   rG  SequentialGUIDerator.__next__r  s:    99;$(("KKMtDJJ'$**455r   )r   )r  r  r  r  r  rg   r+  rG  r|   r  __classcell__)r   s   @r   rL  rL  J  s#    4 	7	76
 Dr   rL  c                   ^^^ T=(       d    / mT=(       d    / mT=(       d    S m[        U 5      nU Vs/ s H/  nT(       a  T" U5      T;   a  M  T(       a  T" U5      T;   a  M-  UPM1     nnUR                  TUS9  T(       a.  [        U Vs/ s H  nT" U5      T;   d  M  UPM     snUU4S jS9mT(       a.  [        U Vs/ s H  nT" U5      T;   d  M  UPM     snUU4S jS9mTU-   T-   $ s  snf s  snf s  snf )a  For when you care about the order of some elements, but not about
others.

Use this to float to the top and/or sink to the bottom a specific
ordering, while sorting the rest of the elements according to
normal :func:`sorted` rules.

>>> soft_sorted(['two', 'b', 'one', 'a'], first=['one', 'two'])
['one', 'two', 'a', 'b']
>>> soft_sorted(range(7), first=[6, 15], last=[2, 4], reverse=True)
[6, 5, 3, 1, 0, 2, 4]
>>> import string
>>> ''.join(soft_sorted(string.hexdigits, first='za1', last='b', key=str.lower))
'aA1023456789cCdDeEfFbB'

Args:
   iterable (list): A list or other iterable to sort.
   first (list): A sequence to enforce for elements which should
      appear at the beginning of the returned list.
   last (list): A sequence to enforce for elements which should
      appear at the end of the returned list.
   key (callable): Callable used to generate a comparable key for
      each item to be sorted, same as the key in
      :func:`sorted`. Note that entries in *first* and *last*
      should be the keys for the items. Defaults to
      passthrough/the identity function.
   reverse (bool): Whether or not elements not explicitly ordered
      by *first* and *last* should be in reverse order or not.

Returns a new list in sorted order.
c                     U $ r&   r'   r0   s    r   r*   soft_sorted.<locals>.<lambda>  s    Ar   r   reversec                 2   > TR                  T" U 5      5      $ r&   index)r)   r   r   s    r   r*   rZ    s    %++VYZ[V\J]r   r   c                 2   > TR                  T" U 5      5      $ r&   r^  )r)   r   lasts    r   r*   rZ    s    

SVWXSYHZr   )r   sortsorted)r=   r   rb  r   r\  seqr)   others    ```    r   soft_sortedrg  ~  s    @ KRE:2D

+C
x.C^1Us1vQDSQRVW[^QE^	JJ3J(3:3a#a&E/3:@]^#8#QQ4q#8>Z[5=4 _ ;8s)   C/C/%C/C4!C4C9C9c                 ~   ^  " U4S jS[         5      nTb  [        T5      (       d  [        ST-  5      e[        XUS9$ )a  A version of :func:`sorted` which will happily sort an iterable of
heterogenous types and return a new list, similar to legacy Python's
behavior.

>>> untyped_sorted(['abc', 2.0, 1, 2, 'def'])
[1, 2.0, 2, 'abc', 'def']

Note how mutually orderable types are sorted as expected, as in
the case of the integers and floats above.

.. note::

   Results may vary across Python versions and builds, but the
   function will produce a sorted list, except in the case of
   explicitly unorderable objects.

c                   ,   > \ rS rSrSrS rU 4S jrSrg) untyped_sorted.<locals>._Wrapperi  r   c                     Xl         g r&   r   )r  r   s     r   r  )untyped_sorted.<locals>._Wrapper.__init__  s    Hr   c                 b  > Tb  T" U R                   5      OU R                   nTb  T" UR                   5      OUR                   n X!:  nU$ ! [         aY    [        U5      R                  [	        [        U5      5      U4[        U5      R                  [	        [        U5      5      U4:  n U$ f = fr&   )r   r   rf   r  r   )r  rf  r   r   r   s       r   __lt__'untyped_sorted.<locals>._Wrapper.__lt__  s    #&?#dhh-C&)oC		N599EJk J  JS	**BtCyM3?;//DK%HIJJs   A AB.-B.N)r  r  r  r  slotsr  rn  r  r`  s   r   _Wrapperrj    s    		 	r   rq  z5expected function or callable object for key, not: %rr[  )objectr3   r   rd  )r=   r   r\  rq  s    `  r   untyped_sortedrs    sE    $6   x}}O  	 ('::r   )NNr&   )Nr   )Ng       @Fr/   )NNNF)Pr  r3  r   r8  r9  r   rP   collections.abcr   r   r   r   r   ImportErrorcollections	typeutilsr   r	   r
   rr  future_builtinsr   r   rg   r6  ra   r   unicoder   ranger{   r   r   r   r"   r   r?   r;   rE   rD   rL   rK   rV   rO   rs   rv   rq   ru   r   r   r   r   boolr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rd   r   r   r  r  r"  r$  rL  	guid_iterseq_guid_iterrg  rs  r'   r   r   <module>r~     s  B	 
     HKK
'8$F.K
	&G$? @	0EP	4$	38	2	F9.+\ ! *0,><"[| Td M`  ?.'!H<~ 2F0:(  /6
 $  . $=| dN3h
I 3& "( 9x .u 9F: :z-: -` L	$&+ \&;P,  HGGGH  (KXF  GuJGLD&s4   D9 E E/ 9EEE,+E,/FF