
    [e0'                        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dS )    )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dAd&Z	edAd'            Z
dBdCd)ZeefdDd,            ZedEd-            ZdFd/ZdGd1ZdHd3ZdId5ZdJd7ZdKd9ZdLd;ZeZdMd<ZdMd=Z xZS )N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                    dS )N    )kvs     (lib/python3.11/site-packages/zict/lru.py<lambda>zLRU.<lambda>]   s         )r   r   r   @Callable[[KT, VT], None] | list[Callable[[KT, VT], None]] | Nonec               B   t                                                       || _        | _        d| _        t          |          r|g}|pg | _        t          |          r|g}|pg | _        | _        fd|	                                D             | _
        t          | j
                                                  | _        t          |          | _        t          fd| j
        	                                D                       | _        d| _        i | _        d S )Nr   c                0    i | ]\  }}| ||          S r(   r(   ).0r)   r*   r   s      r+   
<dictcomp>z LRU.__init__.<locals>.<dictcomp>l   s)    >>>DAq66!Q<<>>>r-   c              3  .   K   | ]\  }}|k    |V  d S Nr(   )r1   r)   r*   r   s      r+   	<genexpr>zLRU.__init__.<locals>.<genexpr>o   s,      'U'UdaaSTffffff'U'Ur-   F)super__init__r   r   r    callabler   r   r   itemsr!   sumvaluesr$   r   r   r   r#   r%   )selfr   r   r   r   r   	__class__s    `   `r+   r7   zLRU.__init__R   s    	H 	" zH BO$$ 	0./O.4">>>>AGGII>>> 3 3 5 566'**
''U'U'U'Udl6H6H6J6J'U'U'UUU
r-   keyr   returnr   c                    | j         |         }| j                            |           | j                            |           |S r4   )r   r   removeadd)r<   r>   results      r+   __getitem__zLRU.__getitem__s   s<    
#
sr-   keysCollection[KT]dict[KT, VT]c                      fd|D             }|D ]6} j                             |            j                             |           7|S )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.
        c                ,    i | ]}|j         |         S r(   r   )r1   r>   r<   s     r+   r2   z*LRU.get_all_or_nothing.<locals>.<dictcomp>   s!    333s#tvc{333r-   )r   rA   rB   )r<   rE   rC   r>   s   `   r+   get_all_or_nothingzLRU.get_all_or_nothingz   s_     4333d333 	  	 CJc"""JNN3r-   valueNonec                   |                      ||           	 |                                  d S # t          $ r | j                            |d          | j        k    r_|| j        vrV	 t          | j                  dk    r,| 	                                 t          | j                  dk    ,n# t          $ r Y nw xY w w xY w)Nr   r'   )
set_noevictevict_until_below_target	Exceptionr!   getr   r   lenr   evict)r<   r>   rL   s      r+   __setitem__zLRU.__setitem__   s    e$$$	))+++++ 		 		 		|Q''$&00S
5J5Jdf++//

 df++//    D		s.   . 7B=&AB+*B=+
B85B=7B88B=c                H   |                      |           |                     ||          }|| j        v r
d| j        |<   || j        |<   | j                            |           || j        k    r| j                            |           || j        |<   | xj	        |z  c_	        dS )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   rB   r   r   r!   r$   )r<   r>   rL   r   s       r+   rO   zLRU.set_noevict   s     	SS%(($$$$&*Ds#s
sDF??JNN3"SV#r-   float | Nonec                    || j         }| j        | j        z   |k    rJ| j        sE	 |                                  n# t
          $ r Y dS w xY w| j        | j        z   |k    r| j        AdS dS dS dS )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#   rT   KeyError)r<   r   s     r+   rP   zLRU.evict_until_below_target   s     9A$+-11$+1

    $+-11$+111111111s   : 
AAKT | NoDefault/tuple[KT, VT, float] | tuple[None, None, float]c                   |t           u rG	 t          t          | j        p| j                            }n# t
          $ r t          d          w xY w|| j        v rdS | j        |         }| j        	                    |           d| j        |<   	 | 
                                5  | j        D ]} |||           | j        |         r,| j        D ]} |||           	 ddd           | j        |= dS 	 ddd           n# 1 swxY w Y   | j        |= n# | j        |= w xY w| j        |= | j                            |           | j                            |          }| xj        |z  c_        |||fS )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   StopIterationrZ   r%   r   rW   unlockr   r   rA   r!   popr$   )r<   r>   rL   cbr   s        r+   rT   z	LRU.evict   s   $ )?4
 8dj99::  ? ? ?=>>>? $$$$ = s
 	
3"'3	( ) )- # #BBsENNNN%c* )"2 ' '3() ) ) ) ) ) "3''')) ) ) ) ) ) ) ) ) ) ) ) ) ) ) "3''"3'''''F3K
#!!#&&V#E6!!s?   (4 AD ";C?D 3D ?DD DD 
Dc                    || j         v r
d| j         |<   | j        |= | j                            |           | j                            |           | xj        | j                            |          z  c_        d S NT)	r%   r   r   rA   r   rW   r$   r!   rb   r<   r>   s     r+   __delitem__zLRU.__delitem__   s|    $$$$&*Ds#F3K
#
3T\--c222r-   KeysView[KT]c                4    | j                                         S r4   )r   rE   r<   s    r+   rE   zLRU.keys   s    v{{}}r-   ValuesView[VT]c                4    | j                                         S r4   )r   r;   rj   s    r+   r;   z
LRU.values   s    v}}r-   ItemsView[KT, VT]c                4    | j                                         S r4   )r   r9   rj   s    r+   r9   z	LRU.items  s    v||~~r-   intc                *    t          | j                  S r4   )rS   r   rj   s    r+   __len__zLRU.__len__  s    46{{r-   Iterator[KT]c                *    t          | j                  S r4   )r_   r   rj   s    r+   __iter__zLRU.__iter__  s    DF||r-   objectc                    || j         v S r4   rJ   rf   s     r+   __contains__zLRU.__contains__  s    df}r-   strc                    t          | j        t                    st          | j                  nd}d| j        | j        z    d| j         d| dS )Ndictz<LRU: /z on >)
isinstancer   rz   rx   r$   r    r   )r<   subs     r+   __str__zLRU.__str__  sQ    !+DFD!9!9Ec$&kkkvL)DK7LL$&LLcLLLLr-   c                .    t          | j                   d S r4   )r   r   rj   s    r+   r   z	LRU.flush  s    dfr-   c                <    d| _         t          | j                   d S re   )r#   r   r   rj   s    r+   r   z	LRU.close  s    dfr-   )
r   r   r   r   r   r.   r   r.   r   r   )r>   r   r?   r   )rE   rF   r?   rG   )r>   r   rL   r   r?   rM   r4   )r   rX   r?   rM   )r>   r[   r?   r\   )r>   r   r?   rM   )r?   rh   )r?   rk   )r?   rm   )r?   ro   )r?   rr   )r>   ru   r?   r"   )r?   rx   )r?   rM   )__name__
__module____qualname____doc____annotations__r7   r   rD   rK   rU   rO   rP   r   rT   rg   rE   r;   r9   rq   rt   rw   r   __repr__r   r   __classcell__)r=   s   @r+   r   r      s        ' 'R !!!!!!!!,,,,3333%%%% HHH MMMLLL!!!!  ,:N               B    V 
 
 
 V
    $ $ $ V$"      $-8" 8" 8" 8" V8"t 3 3 3 V3                  M M M 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 T T T T T T T T T T T T T T T T T ) ) ) ) ) )H H H H H(2r6
 H H H H Hr-   