Skip to content

Commit 44ef974

Browse files
stephenfinzzzeek
authored andcommitted
Misc type hint fixes
A collection of typing-related changes built while typing oslo.cache. Closes: #278 Pull-request: #278 Pull-request-sha: aa04d4d Signed-off-by: Stephen Finucane <stephen@that.guru> Change-Id: I5574404aba72eeb0726418a40e036a4891ce5f33
1 parent b8d20a2 commit 44ef974

15 files changed

Lines changed: 124 additions & 99 deletions

File tree

docs/build/unreleased/278.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
.. change::
2+
:tags: bug, typing
3+
4+
A wide range of typing improvements and modernizations within the codebase.
5+
Pull request courtesy Stephen Finucane.

dogpile/__init__.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
11
__version__ = "1.4.2"
22

3-
from .lock import Lock # noqa
4-
from .lock import NeedRegenerationException # noqa
3+
from .lock import Lock
4+
from .lock import NeedRegenerationException
5+
6+
__all__ = [
7+
"Lock",
8+
"NeedRegenerationException",
9+
"__version__",
10+
]

dogpile/cache/__init__.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
1-
from .region import CacheRegion # noqa
2-
from .region import make_region # noqa
3-
from .region import register_backend # noqa
4-
from .. import __version__ # noqa
1+
from .backends import register_backend
2+
from .region import CacheRegion
3+
from .region import make_region
4+
from .. import __version__
55

66
# backwards compat
7+
8+
__all__ = [
9+
"CacheRegion",
10+
"make_region",
11+
"register_backend",
12+
"__version__",
13+
]

dogpile/cache/api.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
from __future__ import annotations
22

33
import abc
4+
from collections.abc import Callable
5+
from collections.abc import Iterable
6+
from collections.abc import Mapping
7+
from collections.abc import Sequence
48
import enum
59
import pickle
610
import time
711
from typing import Any
8-
from typing import Callable
912
from typing import cast
1013
from typing import Literal
11-
from typing import Mapping
1214
from typing import NamedTuple
1315
from typing import Optional
14-
from typing import Sequence
1516
from typing import Union
1617

1718
from ..util.typing import Self
@@ -297,7 +298,7 @@ def get(self, key: KeyType) -> BackendFormatted: # pragma NO COVERAGE
297298
raise NotImplementedError()
298299

299300
def get_multi(
300-
self, keys: Sequence[KeyType]
301+
self, keys: Iterable[KeyType]
301302
) -> Sequence[BackendFormatted]: # pragma NO COVERAGE
302303
"""Retrieve multiple optionally serialized values from the cache.
303304
@@ -340,7 +341,7 @@ def get_serialized(self, key: KeyType) -> SerializedReturnType:
340341
return cast(SerializedReturnType, self.get(key))
341342

342343
def get_serialized_multi(
343-
self, keys: Sequence[KeyType]
344+
self, keys: Iterable[KeyType]
344345
) -> Sequence[SerializedReturnType]: # pragma NO COVERAGE
345346
"""Retrieve multiple serialized values from the cache.
346347
@@ -478,7 +479,7 @@ def delete(self, key: KeyType) -> None: # pragma NO COVERAGE
478479
raise NotImplementedError()
479480

480481
def delete_multi(
481-
self, keys: Sequence[KeyType]
482+
self, keys: Iterable[KeyType]
482483
) -> None: # pragma NO COVERAGE
483484
"""Delete multiple values from the cache.
484485
@@ -498,12 +499,12 @@ def delete_multi(
498499

499500

500501
class DefaultSerialization:
501-
serializer: Union[None, Serializer] = staticmethod( # type: ignore
502+
serializer: Union[None, Serializer] = staticmethod(
502503
pickle.dumps
503-
)
504-
deserializer: Union[None, Deserializer] = staticmethod( # type: ignore
504+
) # type: ignore
505+
deserializer: Union[None, Deserializer] = staticmethod(
505506
pickle.loads
506-
)
507+
) # type: ignore
507508

508509

509510
class BytesBackend(DefaultSerialization, CacheBackend):
@@ -535,7 +536,7 @@ def get_serialized(self, key: KeyType) -> SerializedReturnType:
535536
raise NotImplementedError()
536537

537538
def get_serialized_multi(
538-
self, keys: Sequence[KeyType]
539+
self, keys: Iterable[KeyType]
539540
) -> Sequence[SerializedReturnType]: # pragma NO COVERAGE
540541
"""Retrieve multiple serialized values from the cache.
541542

dogpile/cache/backends/memcached.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@
66
77
"""
88

9+
from collections.abc import Mapping
910
import random
1011
import threading
1112
import time
1213
import typing
1314
from typing import Any
14-
from typing import Mapping
1515
import warnings
1616

1717
from ..api import CacheBackend

dogpile/cache/plugins/mako_cache.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@
4646
from mako.cache import CacheImpl
4747

4848

49-
class MakoPlugin(CacheImpl):
49+
class MakoPlugin(CacheImpl): # type: ignore[misc]
5050
"""A Mako ``CacheImpl`` which talks to dogpile.cache."""
5151

5252
def __init__(self, cache):

dogpile/cache/proxy.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,10 @@
1212

1313
from __future__ import annotations
1414

15-
from typing import Mapping
15+
from collections.abc import Iterable
16+
from collections.abc import Mapping
17+
from collections.abc import Sequence
1618
from typing import Optional
17-
from typing import Sequence
1819

1920
from .api import BackendFormatted
2021
from .api import BackendSetType
@@ -102,13 +103,13 @@ def set(self, key: KeyType, value: BackendSetType) -> None:
102103
def delete(self, key: KeyType) -> None:
103104
self.proxied.delete(key)
104105

105-
def get_multi(self, keys: Sequence[KeyType]) -> Sequence[BackendFormatted]:
106+
def get_multi(self, keys: Iterable[KeyType]) -> Sequence[BackendFormatted]:
106107
return self.proxied.get_multi(keys)
107108

108109
def set_multi(self, mapping: Mapping[KeyType, BackendSetType]) -> None:
109110
self.proxied.set_multi(mapping)
110111

111-
def delete_multi(self, keys: Sequence[KeyType]) -> None:
112+
def delete_multi(self, keys: Iterable[KeyType]) -> None:
112113
self.proxied.delete_multi(keys)
113114

114115
def get_mutex(self, key: KeyType) -> Optional[CacheMutex]:
@@ -118,7 +119,7 @@ def get_serialized(self, key: KeyType) -> SerializedReturnType:
118119
return self.proxied.get_serialized(key)
119120

120121
def get_serialized_multi(
121-
self, keys: Sequence[KeyType]
122+
self, keys: Iterable[KeyType]
122123
) -> Sequence[SerializedReturnType]:
123124
return self.proxied.get_serialized_multi(keys)
124125

dogpile/cache/region.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
from __future__ import annotations
22

3+
from collections.abc import Callable
4+
from collections.abc import Generator
5+
from collections.abc import Iterable
6+
from collections.abc import Mapping
7+
from collections.abc import Sequence
38
import contextlib
49
import datetime
510
from functools import partial
@@ -10,12 +15,8 @@
1015
import threading
1116
import time
1217
from typing import Any
13-
from typing import Callable
1418
from typing import cast
15-
from typing import Mapping
1619
from typing import Optional
17-
from typing import Sequence
18-
from typing import Tuple
1920
from typing import Type
2021
from typing import TYPE_CHECKING
2122
from typing import Union
@@ -64,7 +65,7 @@
6465
["CacheRegion", KeyType, Callable[[], ValuePayload], CacheMutex], None
6566
]
6667

67-
ExpirationTimeCallable = Callable[[], float]
68+
ExpirationTimeCallable = Callable[[], Optional[float]]
6869

6970
ToStr = Callable[[Any], str]
7071

@@ -648,7 +649,9 @@ def invalidate(self, hard=True):
648649
"""
649650
self.region_invalidator.invalidate(hard)
650651

651-
def configure_from_config(self, config_dict, prefix):
652+
def configure_from_config(
653+
self, config_dict: dict[str, Any], prefix: str
654+
) -> Self:
652655
"""Configure from a configuration dictionary
653656
and a prefix.
654657
@@ -680,7 +683,7 @@ def configure_from_config(self, config_dict, prefix):
680683
),
681684
_config_argument_dict=config_dict,
682685
_config_prefix="%sarguments." % prefix,
683-
wrap=config_dict.get("%swrap" % prefix, None),
686+
wrap=config_dict.get("%swrap" % prefix, None), # type: ignore
684687
replace_existing_backend=config_dict.get(
685688
"%sreplace_existing_backend" % prefix, False
686689
),
@@ -693,7 +696,7 @@ def backend(self):
693696
)
694697

695698
@property
696-
def is_configured(self):
699+
def is_configured(self) -> bool:
697700
"""Return True if the backend has been configured via the
698701
:meth:`.CacheRegion.configure` method already.
699702
@@ -902,7 +905,7 @@ def get_multi(self, keys, expiration_time=None, ignore_expiration=False):
902905
]
903906

904907
@contextlib.contextmanager
905-
def _log_time(self, keys):
908+
def _log_time(self, keys: Iterable[str]) -> Generator[None, None, None]:
906909
start_time = time.time()
907910
yield
908911
seconds = time.time() - start_time
@@ -941,7 +944,7 @@ def get_or_create(
941944
creator: Callable[..., ValuePayload],
942945
expiration_time: Optional[float] = None,
943946
should_cache_fn: Optional[Callable[[ValuePayload], bool]] = None,
944-
creator_args: Optional[Tuple[Any, Mapping[str, Any]]] = None,
947+
creator_args: Optional[tuple[Any, Mapping[str, Any]]] = None,
945948
) -> ValuePayload:
946949
"""Return a cached value based on the given key.
947950
@@ -1104,7 +1107,7 @@ def go():
11041107

11051108
def get_or_create_multi(
11061109
self,
1107-
keys: Sequence[KeyType],
1110+
keys: Iterable[KeyType],
11081111
creator: Callable[[], ValuePayload],
11091112
expiration_time: Optional[float] = None,
11101113
should_cache_fn: Optional[Callable[[ValuePayload], bool]] = None,
@@ -1327,7 +1330,7 @@ def _get_from_backend(self, key: KeyType) -> CacheReturnType:
13271330
return cast(CacheReturnType, self.backend.get(key))
13281331

13291332
def _get_multi_from_backend(
1330-
self, keys: Sequence[KeyType]
1333+
self, keys: Iterable[KeyType]
13311334
) -> Sequence[CacheReturnType]:
13321335
if self.deserializer:
13331336
return [
@@ -1425,7 +1428,7 @@ def delete(self, key: KeyType) -> None:
14251428

14261429
self.backend.delete(key)
14271430

1428-
def delete_multi(self, keys: Sequence[KeyType]) -> None:
1431+
def delete_multi(self, keys: Iterable[KeyType]) -> None:
14291432
"""Remove multiple values from the cache.
14301433
14311434
This operation is idempotent (can be called multiple times, or on a
@@ -1640,9 +1643,7 @@ def get_or_create_for_user_func(key_generator, user_func, *arg, **kw):
16401643
def cache_decorator(user_func):
16411644
if to_str is cast(Callable[[Any], str], str):
16421645
# backwards compatible
1643-
key_generator = _function_key_generator(
1644-
namespace, user_func
1645-
) # type: ignore
1646+
key_generator = _function_key_generator(namespace, user_func)
16461647
else:
16471648
key_generator = _function_key_generator(
16481649
namespace, user_func, to_str

dogpile/cache/util.py

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
1+
from __future__ import annotations
2+
3+
from collections.abc import Callable
4+
from collections.abc import Iterable
15
from hashlib import sha1
6+
from typing import Any
7+
from typing import Union
28

39
from ..util import compat
410
from ..util import langhelpers
511

612

7-
def function_key_generator(namespace, fn, to_str=str):
13+
def function_key_generator(
14+
namespace: str, fn: Callable[..., Any], to_str: Callable[[Any], str] = str
15+
) -> Callable[..., str]:
816
"""Return a function that generates a string
917
key, based on a given function as well as
1018
arguments to the returned function itself.
@@ -45,7 +53,9 @@ def generate_key(*args, **kw):
4553
return generate_key
4654

4755

48-
def function_multi_key_generator(namespace, fn, to_str=str):
56+
def function_multi_key_generator(
57+
namespace: str, fn: Callable[..., Any], to_str: Callable[[Any], str] = str
58+
) -> Callable[..., list[str]]:
4959
if namespace is None:
5060
namespace = "%s:%s" % (fn.__module__, fn.__name__)
5161
else:
@@ -67,7 +77,9 @@ def generate_keys(*args, **kw):
6777
return generate_keys
6878

6979

70-
def kwarg_function_key_generator(namespace, fn, to_str=str):
80+
def kwarg_function_key_generator(
81+
namespace: str, fn: Callable[..., Any], to_str: Callable[[Any], str] = str
82+
) -> Callable[..., str]:
7183
"""Return a function that generates a string
7284
key, based on a given function as well as
7385
arguments to the returned function itself.
@@ -127,22 +139,23 @@ def generate_key(*args, **kwargs):
127139
return generate_key
128140

129141

130-
def sha1_mangle_key(key):
142+
def sha1_mangle_key(key: Union[str, bytes]) -> str:
131143
"""a SHA1 key mangler."""
132144

133-
if isinstance(key, str):
134-
key = key.encode("utf-8")
135-
136-
return sha1(key).hexdigest()
145+
return sha1(
146+
key.encode("utf-8") if isinstance(key, str) else key
147+
).hexdigest()
137148

138149

139-
def length_conditional_mangler(length, mangler):
150+
def length_conditional_mangler(
151+
length: int, mangler: Callable[[str], str]
152+
) -> Callable[[str], str]:
140153
"""a key mangler that mangles if the length of the key is
141154
past a certain threshold.
142155
143156
"""
144157

145-
def mangle(key):
158+
def mangle(key: str) -> str:
146159
if len(key) >= length:
147160
return mangler(key)
148161
else:
@@ -164,14 +177,16 @@ def mangle(key):
164177
class repr_obj:
165178
__slots__ = ("value", "max_chars")
166179

167-
def __init__(self, value, max_chars=300):
180+
def __init__(self, value: Iterable[str], max_chars: int = 300) -> None:
168181
self.value = value
169182
self.max_chars = max_chars
170183

171-
def __eq__(self, other):
172-
return other.value == self.value
184+
def __eq__(self, other: object) -> bool:
185+
if not isinstance(other, repr_obj):
186+
return NotImplemented
187+
return bool(other.value == self.value)
173188

174-
def __repr__(self):
189+
def __repr__(self) -> str:
175190
rep = repr(self.value)
176191
lenrep = len(rep)
177192
if lenrep > self.max_chars:

0 commit comments

Comments
 (0)