Skip to content

Commit 2163179

Browse files
committed
modernize remaining typing constructs
Change-Id: I00fbb4666ff29986539649143270cb9e1e58eb5f
1 parent b3231d7 commit 2163179

File tree

5 files changed

+60
-75
lines changed

5 files changed

+60
-75
lines changed

dogpile/cache/api.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@
1212
from typing import cast
1313
from typing import Literal
1414
from typing import NamedTuple
15-
from typing import Optional
16-
from typing import Union
1715

1816
from ..util.typing import Self
1917

@@ -167,19 +165,19 @@ def age(self) -> float:
167165
return time.time() - self.cached_time
168166

169167

170-
CacheReturnType = Union[CachedValue, NoValueType]
168+
CacheReturnType = CachedValue | NoValueType
171169
"""The non-serialized form of what may be returned from a backend
172170
get method.
173171
174172
"""
175173

176-
SerializedReturnType = Union[bytes, NoValueType]
174+
SerializedReturnType = bytes | NoValueType
177175
"""the serialized form of what may be returned from a backend get method."""
178176

179-
BackendFormatted = Union[CacheReturnType, SerializedReturnType]
177+
BackendFormatted = CacheReturnType | SerializedReturnType
180178
"""Describes the type returned from the :meth:`.CacheBackend.get` method."""
181179

182-
BackendSetType = Union[CachedValue, bytes]
180+
BackendSetType = CachedValue | bytes
183181
"""Describes the value argument passed to the :meth:`.CacheBackend.set`
184182
method."""
185183

@@ -195,23 +193,23 @@ class CacheBackend:
195193
196194
"""
197195

198-
key_mangler: Optional[Callable[[KeyType], KeyType]] = None
196+
key_mangler: Callable[[KeyType], KeyType] | None = None
199197
"""Key mangling function.
200198
201199
May be None, or otherwise declared
202200
as an ordinary instance method.
203201
204202
"""
205203

206-
serializer: Union[None, Serializer] = None
204+
serializer: Serializer | None = None
207205
"""Serializer function that will be used by default if not overridden
208206
by the region.
209207
210208
.. versionadded:: 1.1
211209
212210
"""
213211

214-
deserializer: Union[None, Deserializer] = None
212+
deserializer: Deserializer | None = None
215213
"""deserializer function that will be used by default if not overridden
216214
by the region.
217215
@@ -247,7 +245,7 @@ def from_config_dict(
247245
def has_lock_timeout(self) -> bool:
248246
return False
249247

250-
def get_mutex(self, key: KeyType) -> Optional[CacheMutex]:
248+
def get_mutex(self, key: KeyType) -> CacheMutex | None:
251249
"""Return an optional mutexing object for the given key.
252250
253251
This object need only provide an ``acquire()``
@@ -499,8 +497,8 @@ def delete_multi(
499497

500498

501499
class DefaultSerialization:
502-
serializer: Union[None, Serializer] = staticmethod(pickle.dumps)
503-
deserializer: Union[None, Deserializer] = staticmethod(pickle.loads)
500+
serializer: Serializer | None = staticmethod(pickle.dumps)
501+
deserializer: Deserializer | None = staticmethod(pickle.loads)
504502

505503

506504
class BytesBackend(DefaultSerialization, CacheBackend):

dogpile/cache/proxy.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
from collections.abc import Iterable
1616
from collections.abc import Mapping
1717
from collections.abc import Sequence
18-
from typing import Optional
1918

2019
from .api import BackendFormatted
2120
from .api import BackendSetType
@@ -112,7 +111,7 @@ def set_multi(self, mapping: Mapping[KeyType, BackendSetType]) -> None:
112111
def delete_multi(self, keys: Iterable[KeyType]) -> None:
113112
self.proxied.delete_multi(keys)
114113

115-
def get_mutex(self, key: KeyType) -> Optional[CacheMutex]:
114+
def get_mutex(self, key: KeyType) -> CacheMutex | None:
116115
return self.proxied.get_mutex(key)
117116

118117
def get_serialized(self, key: KeyType) -> SerializedReturnType:

dogpile/cache/region.py

Lines changed: 44 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,8 @@
1616
import time
1717
from typing import Any
1818
from typing import cast
19-
from typing import Optional
2019
from typing import Type
2120
from typing import TYPE_CHECKING
22-
from typing import Union
2321

2422
from decorator import decorate
2523

@@ -65,7 +63,7 @@
6563
["CacheRegion", KeyType, Callable[[], ValuePayload], CacheMutex], None
6664
]
6765

68-
ExpirationTimeCallable = Callable[[], Optional[float]]
66+
ExpirationTimeCallable = Callable[[], float | None]
6967

7068
ToStr = Callable[[Any], str]
7169

@@ -400,13 +398,13 @@ def runner():
400398

401399
def __init__(
402400
self,
403-
name: Optional[str] = None,
401+
name: str | None = None,
404402
function_key_generator: FunctionKeyGenerator = function_key_generator,
405403
function_multi_key_generator: FunctionMultiKeyGenerator = function_multi_key_generator, # noqa E501
406-
key_mangler: Optional[Callable[[KeyType], KeyType]] = None,
407-
serializer: Optional[Callable[[ValuePayload], bytes]] = None,
408-
deserializer: Optional[Callable[[bytes], ValuePayload]] = None,
409-
async_creation_runner: Optional[AsyncCreator] = None,
404+
key_mangler: Callable[[KeyType], KeyType] | None = None,
405+
serializer: Callable[[ValuePayload], bytes] | None = None,
406+
deserializer: Callable[[bytes], ValuePayload] | None = None,
407+
async_creation_runner: AsyncCreator | None = None,
410408
):
411409
"""Construct a new :class:`.CacheRegion`."""
412410
self.name = name
@@ -423,13 +421,13 @@ def __init__(
423421
def configure(
424422
self,
425423
backend: str,
426-
expiration_time: Optional[Union[float, datetime.timedelta]] = None,
427-
arguments: Optional[BackendArguments] = None,
428-
_config_argument_dict: Optional[Mapping[str, Any]] = None,
429-
_config_prefix: Optional[str] = None,
430-
wrap: Sequence[Union[ProxyBackend, Type[ProxyBackend]]] = (),
424+
expiration_time: float | datetime.timedelta | None = None,
425+
arguments: BackendArguments | None = None,
426+
_config_argument_dict: Mapping[str, Any] | None = None,
427+
_config_prefix: str | None = None,
428+
wrap: Sequence[ProxyBackend | Type[ProxyBackend]] = (),
431429
replace_existing_backend: bool = False,
432-
region_invalidator: Optional[RegionInvalidationStrategy] = None,
430+
region_invalidator: RegionInvalidationStrategy | None = None,
433431
) -> Self:
434432
"""Configure a :class:`.CacheRegion`.
435433
@@ -505,10 +503,10 @@ def configure(
505503
else:
506504
self.backend = backend_cls(arguments or {})
507505

508-
self.expiration_time: Union[float, None]
506+
self.expiration_time: float | None
509507

510508
if not expiration_time or isinstance(expiration_time, Number):
511-
self.expiration_time = cast(Union[None, float], expiration_time)
509+
self.expiration_time = cast(None | float, expiration_time)
512510
elif isinstance(expiration_time, datetime.timedelta):
513511
self.expiration_time = int(expiration_time.total_seconds())
514512
else:
@@ -536,7 +534,7 @@ def configure(
536534

537535
return self
538536

539-
def wrap(self, proxy: Union[ProxyBackend, Type[ProxyBackend]]) -> None:
537+
def wrap(self, proxy: ProxyBackend | Type[ProxyBackend]) -> None:
540538
"""Takes a ProxyBackend instance or class and wraps the
541539
attached backend."""
542540

@@ -708,9 +706,9 @@ def is_configured(self) -> bool:
708706
def get(
709707
self,
710708
key: KeyType,
711-
expiration_time: Optional[float] = None,
709+
expiration_time: float | None = None,
712710
ignore_expiration: bool = False,
713-
) -> Union[ValuePayload, NoValueType]:
711+
) -> ValuePayload | NoValueType:
714712
"""Return a value from the cache, based on the given key.
715713
716714
If the value is not present, the method returns the token
@@ -788,9 +786,9 @@ def get(
788786
def get_value_metadata(
789787
self,
790788
key: KeyType,
791-
expiration_time: Optional[float] = None,
789+
expiration_time: float | None = None,
792790
ignore_expiration: bool = False,
793-
) -> Optional[CachedValue]:
791+
) -> CachedValue | None:
794792
"""Return the :class:`.CachedValue` object directly from the cache.
795793
796794
This is the enclosing datastructure that includes the value as well as
@@ -815,7 +813,7 @@ def get_value_metadata(
815813
def _get_cache_value(
816814
self,
817815
key: KeyType,
818-
expiration_time: Optional[float] = None,
816+
expiration_time: float | None = None,
819817
ignore_expiration: bool = False,
820818
) -> CacheReturnType:
821819
if self.key_mangler:
@@ -827,7 +825,7 @@ def _get_cache_value(
827825
return value
828826

829827
def _unexpired_value_fn(
830-
self, expiration_time: Optional[float], ignore_expiration: bool
828+
self, expiration_time: float | None, ignore_expiration: bool
831829
) -> Callable[[CacheReturnType], CacheReturnType]:
832830
if ignore_expiration:
833831
return lambda value: value
@@ -942,9 +940,9 @@ def get_or_create(
942940
self,
943941
key: KeyType,
944942
creator: Callable[..., ValuePayload],
945-
expiration_time: Optional[float] = None,
946-
should_cache_fn: Optional[Callable[[ValuePayload], bool]] = None,
947-
creator_args: Optional[tuple[Any, Mapping[str, Any]]] = None,
943+
expiration_time: float | None = None,
944+
should_cache_fn: Callable[[ValuePayload], bool] | None = None,
945+
creator_args: tuple[Any, Mapping[str, Any]] | None = None,
948946
) -> ValuePayload:
949947
"""Return a cached value based on the given key.
950948
@@ -1077,7 +1075,7 @@ def gen_value():
10771075
if expiration_time == -1:
10781076
expiration_time = None
10791077

1080-
async_creator: Optional[Callable[[CacheMutex], AsyncCreator]]
1078+
async_creator: Callable[[CacheMutex], AsyncCreator] | None
10811079
if self.async_creation_runner:
10821080
acr = self.async_creation_runner
10831081

@@ -1109,8 +1107,8 @@ def get_or_create_multi(
11091107
self,
11101108
keys: Iterable[KeyType],
11111109
creator: Callable[[], ValuePayload],
1112-
expiration_time: Optional[float] = None,
1113-
should_cache_fn: Optional[Callable[[ValuePayload], bool]] = None,
1110+
expiration_time: float | None = None,
1111+
should_cache_fn: Callable[[ValuePayload], bool] | None = None,
11141112
) -> Sequence[ValuePayload]:
11151113
"""Return a sequence of cached values based on a sequence of keys.
11161114
@@ -1257,7 +1255,7 @@ def async_creator(mutexes, key, mutex):
12571255
mutex.release()
12581256

12591257
def _value(
1260-
self, value: Any, metadata: Optional[MetaDataType] = None
1258+
self, value: Any, metadata: MetaDataType | None = None
12611259
) -> CachedValue:
12621260
"""Return a :class:`.CachedValue` given a value."""
12631261

@@ -1294,7 +1292,7 @@ def _serialize_cached_value_elements(
12941292
)
12951293

12961294
def _serialized_payload(
1297-
self, payload: ValuePayload, metadata: Optional[MetaDataType] = None
1295+
self, payload: ValuePayload, metadata: MetaDataType | None = None
12981296
) -> BackendFormatted:
12991297
"""Return a backend formatted representation of a value.
13001298
@@ -1446,11 +1444,11 @@ def delete_multi(self, keys: Iterable[KeyType]) -> None:
14461444

14471445
def cache_on_arguments(
14481446
self,
1449-
namespace: Optional[str] = None,
1450-
expiration_time: Union[float, ExpirationTimeCallable, None] = None,
1451-
should_cache_fn: Optional[Callable[[ValuePayload], bool]] = None,
1447+
namespace: str | None = None,
1448+
expiration_time: float | ExpirationTimeCallable | None = None,
1449+
should_cache_fn: Callable[[ValuePayload], bool] | None = None,
14521450
to_str: Callable[[Any], str] = str,
1453-
function_key_generator: Optional[FunctionKeyGenerator] = None,
1451+
function_key_generator: FunctionKeyGenerator | None = None,
14541452
) -> Callable[[Callable[..., ValuePayload]], Callable[..., ValuePayload]]:
14551453
"""A function decorator that will cache the return
14561454
value of the function using a key derived from the
@@ -1631,10 +1629,10 @@ def somemethod(self, x, y):
16311629
def get_or_create_for_user_func(key_generator, user_func, *arg, **kw):
16321630
key = key_generator(*arg, **kw)
16331631

1634-
timeout: Optional[float] = (
1632+
timeout: float | None = (
16351633
cast(ExpirationTimeCallable, expiration_time)()
16361634
if expiration_time_is_callable
1637-
else cast(Optional[float], expiration_time)
1635+
else cast(float | None, expiration_time)
16381636
)
16391637
return self.get_or_create(
16401638
key, user_func, timeout, should_cache_fn, (arg, kw)
@@ -1686,19 +1684,15 @@ def get(*arg, **kw):
16861684

16871685
def cache_multi_on_arguments(
16881686
self,
1689-
namespace: Optional[str] = None,
1690-
expiration_time: Union[float, ExpirationTimeCallable, None] = None,
1691-
should_cache_fn: Optional[Callable[[ValuePayload], bool]] = None,
1687+
namespace: str | None = None,
1688+
expiration_time: float | ExpirationTimeCallable | None = None,
1689+
should_cache_fn: Callable[[ValuePayload], bool] | None = None,
16921690
asdict: bool = False,
16931691
to_str: ToStr = str,
1694-
function_multi_key_generator: Optional[
1695-
FunctionMultiKeyGenerator
1696-
] = None,
1692+
function_multi_key_generator: FunctionMultiKeyGenerator | None = None,
16971693
) -> Callable[
16981694
[Callable[..., Sequence[ValuePayload]]],
1699-
Callable[
1700-
..., Union[Sequence[ValuePayload], Mapping[KeyType, ValuePayload]]
1701-
],
1695+
Callable[..., Sequence[ValuePayload] | Mapping[KeyType, ValuePayload]],
17021696
]:
17031697
"""A function decorator that will cache multiple return
17041698
values from the function using a sequence of keys derived from the
@@ -1828,7 +1822,7 @@ def get_or_create_for_user_func(
18281822
user_func: Callable[..., Sequence[ValuePayload]],
18291823
*arg: Any,
18301824
**kw: Any,
1831-
) -> Union[Sequence[ValuePayload], Mapping[KeyType, ValuePayload]]:
1825+
) -> Sequence[ValuePayload] | Mapping[KeyType, ValuePayload]:
18321826
cache_keys = arg
18331827
keys = key_generator(*arg, **kw)
18341828
key_lookup = dict(zip(keys, cache_keys))
@@ -1837,15 +1831,13 @@ def get_or_create_for_user_func(
18371831
def creator(*keys_to_create):
18381832
return user_func(*[key_lookup[k] for k in keys_to_create])
18391833

1840-
timeout: Optional[float] = (
1834+
timeout: float | None = (
18411835
cast(ExpirationTimeCallable, expiration_time)()
18421836
if expiration_time_is_callable
1843-
else cast(Optional[float], expiration_time)
1837+
else cast(float | None, expiration_time)
18441838
)
18451839

1846-
result: Union[
1847-
Sequence[ValuePayload], Mapping[KeyType, ValuePayload]
1848-
]
1840+
result: Sequence[ValuePayload] | Mapping[KeyType, ValuePayload]
18491841

18501842
if asdict:
18511843

dogpile/cache/util.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
from collections.abc import Iterable
55
from hashlib import sha1
66
from typing import Any
7-
from typing import Union
87

98
from ..util import compat
109
from ..util import langhelpers
@@ -139,7 +138,7 @@ def generate_key(*args, **kwargs):
139138
return generate_key
140139

141140

142-
def sha1_mangle_key(key: Union[str, bytes]) -> str:
141+
def sha1_mangle_key(key: str | bytes) -> str:
143142
"""a SHA1 key mangler."""
144143

145144
return sha1(

0 commit comments

Comments
 (0)