1
1
import pickle
2
+ from types import TracebackType
3
+ from typing import Any , Optional , Type
2
4
import redis
5
+ import sys
3
6
from .abstract_cache_base import AbstractCache
4
7
8
+ if sys .version_info >= (3 , 11 ):
9
+ from typing import Self
10
+ else :
11
+ from typing_extensions import Self
12
+
5
13
6
14
class RedisCache (AbstractCache ):
7
15
"""
@@ -24,7 +32,7 @@ class RedisCache(AbstractCache):
24
32
__exit__(self, exc_type, exc_value, traceback): Context management exit.
25
33
"""
26
34
27
- def __init__ (self , seed , redis_url ):
35
+ def __init__ (self , seed : str , redis_url : str ):
28
36
"""
29
37
Initialize the RedisCache instance.
30
38
@@ -36,7 +44,7 @@ def __init__(self, seed, redis_url):
36
44
self .seed = seed
37
45
self .cache = redis .Redis .from_url (redis_url )
38
46
39
- def _prefixed_key (self , key ) :
47
+ def _prefixed_key (self , key : str ) -> str :
40
48
"""
41
49
Get a namespaced key for the cache.
42
50
@@ -48,7 +56,7 @@ def _prefixed_key(self, key):
48
56
"""
49
57
return f"autogen:{ self .seed } :{ key } "
50
58
51
- def get (self , key , default = None ):
59
+ def get (self , key : str , default : Optional [ Any ] = None ) -> Any :
52
60
"""
53
61
Retrieve an item from the Redis cache.
54
62
@@ -65,7 +73,7 @@ def get(self, key, default=None):
65
73
return default
66
74
return pickle .loads (result )
67
75
68
- def set (self , key , value ) :
76
+ def set (self , key : str , value : Any ) -> None :
69
77
"""
70
78
Set an item in the Redis cache.
71
79
@@ -79,15 +87,15 @@ def set(self, key, value):
79
87
serialized_value = pickle .dumps (value )
80
88
self .cache .set (self ._prefixed_key (key ), serialized_value )
81
89
82
- def close (self ):
90
+ def close (self ) -> None :
83
91
"""
84
92
Close the Redis client.
85
93
86
94
Perform any necessary cleanup, such as closing network connections.
87
95
"""
88
96
self .cache .close ()
89
97
90
- def __enter__ (self ):
98
+ def __enter__ (self ) -> Self :
91
99
"""
92
100
Enter the runtime context related to the object.
93
101
@@ -96,7 +104,9 @@ def __enter__(self):
96
104
"""
97
105
return self
98
106
99
- def __exit__ (self , exc_type , exc_value , traceback ):
107
+ def __exit__ (
108
+ self , exc_type : Optional [Type [BaseException ]], exc_val : Optional [BaseException ], exc_tb : Optional [TracebackType ]
109
+ ) -> None :
100
110
"""
101
111
Exit the runtime context related to the object.
102
112
0 commit comments