1
+ from __future__ import annotations
1
2
import time
2
- from collections .abc import MutableMapping
3
+ from typing import MutableMapping , List , TypedDict , Iterator , Any
4
+
3
5
from functools import lru_cache
4
6
5
7
6
- class DirCache (MutableMapping ):
8
+ class DirEntry (TypedDict ):
9
+ name : str
10
+ size : int
11
+ type : str
12
+
13
+
14
+ class DirCache (MutableMapping [str , List [DirEntry ]]):
7
15
"""
8
16
Caching of directory listings, in a structure like::
9
17
@@ -26,10 +34,10 @@ class DirCache(MutableMapping):
26
34
27
35
def __init__ (
28
36
self ,
29
- use_listings_cache = True ,
30
- listings_expiry_time = None ,
31
- max_paths = None ,
32
- ** kwargs ,
37
+ use_listings_cache : bool = True ,
38
+ listings_expiry_time : float | None = None ,
39
+ max_paths : int | None = None ,
40
+ ** kwargs : Any ,
33
41
):
34
42
"""
35
43
@@ -45,36 +53,36 @@ def __init__(
45
53
The number of most recent listings that are considered valid; 'recent'
46
54
refers to when the entry was set.
47
55
"""
48
- self ._cache = {}
49
- self ._times = {}
56
+ self ._cache : dict [ str , list [ DirEntry ]] = {}
57
+ self ._times : dict [ str , float ] = {}
50
58
if max_paths :
51
59
self ._q = lru_cache (max_paths + 1 )(lambda key : self ._cache .pop (key , None ))
52
60
self .use_listings_cache = use_listings_cache
53
61
self .listings_expiry_time = listings_expiry_time
54
62
self .max_paths = max_paths
55
63
56
- def __getitem__ (self , item ) :
64
+ def __getitem__ (self , item : str ) -> list [ DirEntry ] :
57
65
if self .listings_expiry_time is not None :
58
66
if self ._times .get (item , 0 ) - time .time () < - self .listings_expiry_time :
59
67
del self ._cache [item ]
60
68
if self .max_paths :
61
69
self ._q (item )
62
70
return self ._cache [item ] # maybe raises KeyError
63
71
64
- def clear (self ):
72
+ def clear (self ) -> None :
65
73
self ._cache .clear ()
66
74
67
- def __len__ (self ):
75
+ def __len__ (self ) -> int :
68
76
return len (self ._cache )
69
77
70
- def __contains__ (self , item ) :
78
+ def __contains__ (self , item : object ) -> bool :
71
79
try :
72
- self [item ]
80
+ self [item ] # type: ignore[index]
73
81
return True
74
82
except KeyError :
75
83
return False
76
84
77
- def __setitem__ (self , key , value ) :
85
+ def __setitem__ (self , key : str , value : List [ DirEntry ]) -> None :
78
86
if not self .use_listings_cache :
79
87
return
80
88
if self .max_paths :
@@ -83,10 +91,10 @@ def __setitem__(self, key, value):
83
91
if self .listings_expiry_time is not None :
84
92
self ._times [key ] = time .time ()
85
93
86
- def __delitem__ (self , key ):
94
+ def __delitem__ (self , key ) -> None :
87
95
del self ._cache [key ]
88
96
89
- def __iter__ (self ):
97
+ def __iter__ (self ) -> Iterator [ str ] :
90
98
entries = list (self ._cache )
91
99
92
100
return (k for k in entries if k in self )
0 commit comments