
    Be0'                        d dl mZ d dlmZmZmZmZmZmZm	Z	 d dl
mZmZmZmZmZmZmZmZ d dlmZ  G d deeef         Zy)    )annotations)Callable
Collection	ItemsViewIteratorKeysViewMutableMapping
ValuesView)KTVT	NoDefaultZictBasecloseflushlocked	nodefault)InsertionSortedSetc                  ~    e Zd ZU dZded<   ded<   ded<   ded<   ded	<   d
ed<   ded<   ded<   ded<   ded<   ded<   ded<   ddd d	 	 	 	 	 	 	 	 	 d* fdZed+d       Zed,d       Zd-dZ	ed-d       Z
d.d/dZeef	 	 	 d0d       Zed1d        Zd2d!Zd3d"Zd4d#Zd5d$Zd6d%Zd7d&Zd8d'ZeZd9d(Zd9d)Z xZS ):LRUa  Evict Least Recently Used Elements.

    Parameters
    ----------
    n: int or float
        Number of elements to keep, or total weight if ``weight`` is used.
        Any individual key that is heavier than n will be automatically evicted as soon
        as it is inserted.

        It can be updated after initialization. See also: ``offset`` attribute.
    d: MutableMapping
        Dict-like in which to hold elements. There are no expectations on its internal
        ordering. Iteration on the LRU follows the order of the underlying mapping.
    on_evict: callable or list of callables
        Function:: k, v -> action to call on key/value pairs prior to eviction
        If an exception occurs during an on_evict callback (e.g a callback tried
        storing to disk and raised a disk full error) the key will remain in the LRU.
    on_cancel_evict: callable or list of callables
        Function:: k, v -> action to call on key/value pairs if they're deleted or
        updated from a thread while the on_evict callables are being executed in
        another.
        If you're not accessing the LRU from multiple threads, ignore this parameter.
    weight: callable
        Function:: k, v -> number to determine the size of keeping the item in
        the mapping.  Defaults to ``(k, v) -> 1``

    Notes
    -----
    If you call methods of this class from multiple threads, access will be fast as long
    as all methods of ``d`` are fast. Callbacks are not protected by locks and can be
    arbitrarily slow.

    Examples
    --------
    >>> lru = LRU(2, {}, on_evict=lambda k, v: print("Lost", k, v))
    >>> lru['x'] = 1
    >>> lru['y'] = 2
    >>> lru['z'] = 3
    Lost x 1
    MutableMapping[KT, VT]dzInsertionSortedSet[KT]orderheavyzlist[Callable[[KT, VT], None]]on_evicton_cancel_evictCallable[[KT, VT], float]weightfloatnoffsetzdict[KT, float]weightsboolclosedtotal_weightzdict[KT, bool]_cancel_evictNc                     y)N    )kvs     (lib/python3.12/site-packages/zict/lru.py<lambda>zLRU.<lambda>]   s        )r   r   r   c          	        t         |           || _        | _        d| _        t        |      r|g}|xs g | _        t        |      r|g}|xs g | _        || _        |j                         D ci c]  \  }}| |||       c}}| _
        t        | j                  j                               | _        t        |      | _        t        fd| j                  j                         D              | _        d| _        i | _        y c c}}w )Nr   c              3  4   K   | ]  \  }}|k\  s|  y wNr(   ).0r)   r*   r   s      r+   	<genexpr>zLRU.__init__.<locals>.<genexpr>o   s     'UdaaSTf'Us   F)super__init__r   r   r    callabler   r   r   itemsr!   sumvaluesr$   r   r   r   r#   r%   )	selfr   r   r   r   r   r)   r*   	__class__s	    `      r+   r4   zLRU.__init__R   s     	H zH BO$./O.4"45GGI>DAq6!Q<> 3 3 56'*
''Udll6H6H6J'UU
 ?s   2Dc                    | j                   |   }| j                  j                  |       | j                  j                  |       |S r0   r   r   removeadd)r9   keyresults      r+   __getitem__zLRU.__getitem__s   s6    

#

sr-   c                    |D ci c]  }|| j                   |    }}|D ]8  }| j                  j                  |       | j                  j                  |       : |S c c}w )a8  If all keys exist in the LRU, update their FIFO priority and return their
        values; this would be the same as ``{k: lru[k] for k in keys}``.
        If any keys are missing, however, raise KeyError for the first one missing and
        do not bring any of the available keys to the top of the LRU.
        r<   )r9   keysr?   r@   s       r+   get_all_or_nothingzLRU.get_all_or_nothingz   sa     /33s#tvvc{"33 	 CJJc"JJNN3	  	 4s   Ac                x   | j                  ||       	 | j                          y # t        $ r | j                  j	                  |d      | j
                  kD  r`|| j                  vrR	 t        | j                        dkD  r)| j                          t        | j                        dkD  r) # t        $ r Y  w xY w w xY w)Nr   r'   )
set_noevictevict_until_below_target	Exceptionr!   getr   r   lenr   evict)r9   r?   values      r+   __setitem__zLRU.__setitem__   s    e$	))+ 		||Q'$&&0S

5Jdff+/

 dff+/  ! 		s/   % A B9&A B('B9(	B41B93B44B9c                t   | j                  |       | j                  ||      }|| j                  v rd| j                  |<   || j                  |<   | j                  j                  |       || j                  kD  r| j                  j                  |       || j                  |<   | xj                  |z  c_	        y)a<  Variant of ``__setitem__`` that does not evict if the total weight exceeds n.
        Unlike ``__setitem__``, this method does not depend on the ``on_evict``
        functions to be thread-safe for its own thread-safety. It also is not prone to
        re-raising exceptions from the ``on_evict`` callbacks.
        TN)
discardr   r%   r   r   r>   r   r   r!   r$   )r9   r?   rL   r   s       r+   rF   zLRU.set_noevict   s     	SS%($$$$&*Ds#s

sDFF?JJNN3"SV#r-   c                   || j                   }| j                  | j                  z   |kD  rI| j                  s<	 | j	                          | j                  | j                  z   |kD  r| j                  s:yyyy# t
        $ r Y yw xY w)zEvict key/value pairs until the total weight falls below n

        Parameters
        ----------
        n: float, optional
            Total weight threshold to achieve. Defaults to self.n.
        N)r   r$   r    r#   rK   KeyError)r9   r   s     r+   rG   zLRU.evict_until_below_target   sx     9A$++-1$++

 $++-1$++1+1  s   A5 5	B Bc                &   |t         u r-	 t        t        | j                  xs | j                              }|| j                  v ry| j                  |   }| j                  j                  |       d| j                  |<   	 | j                         5  | j                  D ]  } |||        | j                  |   r1| j                  D ]  } |||        	 ddd       | j                  |= y	 ddd       | j                  |= | j                  |= | j                  j                  |       | j                  j                  |      }| xj                   |z  c_        |||fS # t
        $ r t        d      w xY w# 1 sw Y   xY w# | j                  |= w xY w)a$  Evict least recently used key, or least recently inserted key with individual
        weight > n, if any. You may also evict a specific key.

        This is typically called from internal use, but can be externally
        triggered as well.

        Returns
        -------
        Tuple of (key, value, weight)

        Or (None, None, 0) if the key that was being evicted was updated or deleted from
        another thread while the on_evict callbacks were being executed. This outcome is
        only possible in multithreaded access.
        zevict(): dictionary is empty)NNr   FN)r   nextiterr   r   StopIterationrQ   r%   r   rO   unlockr   r   r=   r!   popr$   )r9   r?   rL   cbr   s        r+   rK   z	LRU.evict   s   $ )?4

 8djj9: $$$$  s
 	

3"'3	( )-- #BsEN# %%c*"22 '3'() ""3' +) ""3'FF3K

#!!#&V#E6!!I ! ?=>>?&) ) ""3's6   ,E ?F AE5F +F E25E>:F Fc                    || j                   v rd| j                   |<   | j                  |= | j                  j                  |       | j                  j                  |       | xj                  | j                  j                  |      z  c_        y NT)	r%   r   r   r=   r   rO   r$   r!   rW   r9   r?   s     r+   __delitem__zLRU.__delitem__   so    $$$$&*Ds#FF3K

#

3T\\--c22r-   c                6    | j                   j                         S r0   )r   rC   r9   s    r+   rC   zLRU.keys   s    vv{{}r-   c                6    | j                   j                         S r0   )r   r8   r^   s    r+   r8   z
LRU.values   s    vv}}r-   c                6    | j                   j                         S r0   )r   r6   r^   s    r+   r6   z	LRU.items  s    vv||~r-   c                ,    t        | j                        S r0   )rJ   r   r^   s    r+   __len__zLRU.__len__  s    466{r-   c                ,    t        | j                        S r0   )rT   r   r^   s    r+   __iter__zLRU.__iter__  s    DFF|r-   c                    || j                   v S r0   )r   r[   s     r+   __contains__zLRU.__contains__  s    dff}r-   c                    t        | j                  t              st        | j                        nd}d| j                  | j
                  z    d| j                   d| dS )Ndictz<LRU: /z on >)
isinstancer   rh   strr$   r    r   )r9   subs     r+   __str__zLRU.__str__  sM    !+DFFD!9c$&&kv))DKK78$&&cU!LLr-   c                .    t        | j                         y r0   )r   r   r^   s    r+   r   z	LRU.flush  s    dffr-   c                <    d| _         t        | j                         y rZ   )r#   r   r   r^   s    r+   r   z	LRU.close  s    dffr-   )
r   r   r   r   r   @Callable[[KT, VT], None] | list[Callable[[KT, VT], None]] | Noner   rq   r   r   )r?   r   returnr   )rC   zCollection[KT]rr   zdict[KT, VT])r?   r   rL   r   rr   Noner0   )r   zfloat | Nonerr   rs   )r?   zKT | NoDefaultrr   z/tuple[KT, VT, float] | tuple[None, None, float])r?   r   rr   rs   )rr   zKeysView[KT])rr   zValuesView[VT])rr   zItemsView[KT, VT])rr   int)rr   zIterator[KT])r?   objectrr   r"   )rr   rl   )rr   rs   )__name__
__module____qualname____doc____annotations__r4   r   rA   rD   rM   rF   rG   r   rK   r\   rC   r8   r6   rb   rd   rf   rn   __repr__r   r   __classcell__)r:   s   @r+   r   r      sN   'R !!!!,,33%% H ML!!  ,:   " 
   * B   
 
 $ $"  $-8"!8"	88" 8"t 3 3M Hr-   r   N)
__future__r   collections.abcr   r   r   r   r   r	   r
   zict.commonr   r   r   r   r   r   r   r   
zict.utilsr   r   r(   r-   r+   <module>r      s=    "   U T T )H(2r6
 Hr-   