Skip to content

Commit 76a34e2

Browse files
jackgerritsekzhu
andauthored
Resolve type issues in redis cache (#1872)
Co-authored-by: Eric Zhu <[email protected]>
1 parent 195033e commit 76a34e2

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

autogen/cache/redis_cache.py

+17-7
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
11
import pickle
2+
from types import TracebackType
3+
from typing import Any, Optional, Type
24
import redis
5+
import sys
36
from .abstract_cache_base import AbstractCache
47

8+
if sys.version_info >= (3, 11):
9+
from typing import Self
10+
else:
11+
from typing_extensions import Self
12+
513

614
class RedisCache(AbstractCache):
715
"""
@@ -24,7 +32,7 @@ class RedisCache(AbstractCache):
2432
__exit__(self, exc_type, exc_value, traceback): Context management exit.
2533
"""
2634

27-
def __init__(self, seed, redis_url):
35+
def __init__(self, seed: str, redis_url: str):
2836
"""
2937
Initialize the RedisCache instance.
3038
@@ -36,7 +44,7 @@ def __init__(self, seed, redis_url):
3644
self.seed = seed
3745
self.cache = redis.Redis.from_url(redis_url)
3846

39-
def _prefixed_key(self, key):
47+
def _prefixed_key(self, key: str) -> str:
4048
"""
4149
Get a namespaced key for the cache.
4250
@@ -48,7 +56,7 @@ def _prefixed_key(self, key):
4856
"""
4957
return f"autogen:{self.seed}:{key}"
5058

51-
def get(self, key, default=None):
59+
def get(self, key: str, default: Optional[Any] = None) -> Any:
5260
"""
5361
Retrieve an item from the Redis cache.
5462
@@ -65,7 +73,7 @@ def get(self, key, default=None):
6573
return default
6674
return pickle.loads(result)
6775

68-
def set(self, key, value):
76+
def set(self, key: str, value: Any) -> None:
6977
"""
7078
Set an item in the Redis cache.
7179
@@ -79,15 +87,15 @@ def set(self, key, value):
7987
serialized_value = pickle.dumps(value)
8088
self.cache.set(self._prefixed_key(key), serialized_value)
8189

82-
def close(self):
90+
def close(self) -> None:
8391
"""
8492
Close the Redis client.
8593
8694
Perform any necessary cleanup, such as closing network connections.
8795
"""
8896
self.cache.close()
8997

90-
def __enter__(self):
98+
def __enter__(self) -> Self:
9199
"""
92100
Enter the runtime context related to the object.
93101
@@ -96,7 +104,9 @@ def __enter__(self):
96104
"""
97105
return self
98106

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:
100110
"""
101111
Exit the runtime context related to the object.
102112

0 commit comments

Comments
 (0)