persistent-function-cache 0.2.0__py3-none-any.whl → 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,90 @@
1
+ import inspect
2
+ import pickle
3
+ from collections.abc import Callable, Iterable, Iterator
4
+ from dataclasses import dataclass
5
+ from functools import cached_property
6
+ from typing import Any
7
+
8
+ from persistent_cache.models import Path
9
+ from persistent_cache.reducers.base import Reducer
10
+
11
+ from . import hashing
12
+
13
+
14
+ @dataclass
15
+ class CacheSlot:
16
+ function: Callable[..., Any]
17
+ args: tuple[Any, ...]
18
+ kwargs: dict[str, Any]
19
+ directory: Path
20
+ key_arguments: Iterable[str] | str | None
21
+ extra_keys: Any
22
+ key_reducer: type[Reducer] | None
23
+ deep_learning: bool
24
+ speedup_deep_learning: bool
25
+
26
+ @property
27
+ def value(self) -> Any:
28
+ try:
29
+ with self.path.open("rb") as fp:
30
+ return pickle.Unpickler(fp).load() # noqa: S301
31
+ except (pickle.UnpicklingError, EOFError):
32
+ # discard values of corrupted or empty slots
33
+ raise KeyError from None
34
+
35
+ @value.setter
36
+ def value(self, value: Any) -> None:
37
+ self.path.byte_content = pickle.dumps(value)
38
+
39
+ @cached_property
40
+ def path(self) -> Path:
41
+ return (
42
+ self.directory
43
+ / self.function.__module__.replace(".", "_")
44
+ / self.function.__name__
45
+ / hashing.compute_hash(self.reducer, self.keys)
46
+ )
47
+
48
+ @property
49
+ def keys(self) -> Iterator[Any]:
50
+ yield self.function
51
+ is_iterable = isinstance(self.extra_keys, Iterable) and not isinstance(
52
+ self.extra_keys,
53
+ str | bytes | bytearray,
54
+ )
55
+ if is_iterable:
56
+ yield from self.extra_keys
57
+ else:
58
+ yield self.extra_keys
59
+ yield from self.argument_values
60
+
61
+ @property
62
+ def argument_values(self) -> Iterator[Any]:
63
+ if self.key_arguments is None:
64
+ yield from self.args
65
+ yield from self.kwargs.values()
66
+ else:
67
+ arguments = inspect.signature(self.function).bind(*self.args, **self.kwargs)
68
+ arguments.apply_defaults()
69
+ if isinstance(self.key_arguments, str):
70
+ yield arguments.arguments.get(self.key_arguments)
71
+ else:
72
+ for name in self.key_arguments:
73
+ yield arguments.arguments.get(name)
74
+
75
+ @property
76
+ def reducer(self) -> type[Reducer]:
77
+ if self.key_reducer is not None:
78
+ return self.key_reducer
79
+ if self.deep_learning:
80
+ from persistent_cache.reducers.deep_learning import Reducer as Reducer_
81
+
82
+ return Reducer_
83
+ if self.speedup_deep_learning:
84
+ from persistent_cache.reducers.speedup_deep_learning import (
85
+ Reducer as Reducer_,
86
+ )
87
+
88
+ return Reducer_
89
+
90
+ return Reducer
@@ -1,20 +1,22 @@
1
- import inspect
2
- from collections.abc import Callable, Iterator
1
+ from collections.abc import Callable, Iterable
3
2
  from functools import wraps
4
- from typing import Any, cast, overload
3
+ from typing import Any, TypeVar, cast, overload
5
4
 
6
- from persistent_cache.models import F, Path
5
+ from persistent_cache.models import Path
7
6
  from persistent_cache.reducers.base import Reducer
8
7
 
9
- from .cacheslot import CacheSlot
8
+ from .cache_slot import CacheSlot
9
+
10
+ F = TypeVar("F", bound=Callable[..., Any])
10
11
 
11
12
 
12
13
  @overload
13
14
  def cache(
14
15
  function: F,
15
16
  *,
16
- cache_path: Path = Path.cache,
17
- cache_key_arguments: tuple[str, ...] | str | None = None,
17
+ cache_directory: Path = Path.cache,
18
+ cache_key_arguments: Iterable[str] | str | None = None,
19
+ extra_cache_keys: Iterable[Any] | None = None,
18
20
  key_reducer: type[Reducer] = Reducer,
19
21
  deep_learning: bool = False,
20
22
  speedup_deep_learning: bool = False,
@@ -25,8 +27,9 @@ def cache(
25
27
  def cache(
26
28
  function: None = None,
27
29
  *,
28
- cache_path: Path = Path.cache,
29
- cache_key_arguments: tuple[str, ...] | str | None = None,
30
+ cache_directory: Path = Path.cache,
31
+ cache_key_arguments: Iterable[str] | str | None = None,
32
+ extra_cache_keys: Any = None,
30
33
  key_reducer: type[Reducer] = Reducer,
31
34
  deep_learning: bool = False,
32
35
  speedup_deep_learning: bool = False,
@@ -36,8 +39,9 @@ def cache(
36
39
  def cache( # noqa: PLR0913
37
40
  function: F | None = None,
38
41
  *,
39
- cache_path: Path = Path.cache,
40
- cache_key_arguments: tuple[str, ...] | str | None = None,
42
+ cache_directory: Path = Path.cache,
43
+ cache_key_arguments: Iterable[str] | str | None = None,
44
+ extra_cache_keys: Any = None,
41
45
  key_reducer: type[Reducer] | None = None,
42
46
  deep_learning: bool = False,
43
47
  speedup_deep_learning: bool = False,
@@ -55,68 +59,29 @@ def cache( # noqa: PLR0913
55
59
  ...
56
60
  """
57
61
 
58
- reducer = extract_reducer(
59
- key_reducer,
60
- deep_learning=deep_learning,
61
- speedup_deep_learning=speedup_deep_learning,
62
- )
63
-
64
- def cache_decorator(function: F) -> F:
65
- @wraps(function)
62
+ def cache_decorator(function_: F) -> F:
63
+ @wraps(function_)
66
64
  def wrapped_function(*args: Any, **kwargs: Any) -> Any:
67
- arguments = tuple(
68
- extract_argument_values(function, args, kwargs, cache_key_arguments),
65
+ cache_slot = CacheSlot(
66
+ function_,
67
+ args,
68
+ kwargs,
69
+ cache_directory,
70
+ cache_key_arguments,
71
+ extra_cache_keys,
72
+ key_reducer,
73
+ deep_learning,
74
+ speedup_deep_learning,
69
75
  )
70
- cache_slot = CacheSlot(function, arguments, reducer, cache_path)
71
76
  try:
72
- value = cache_slot.value
77
+ result = cache_slot.value
73
78
  except KeyError:
74
- value = function(*args, **kwargs)
75
- cache_slot.value = value
76
- return value
79
+ result = function_(*args, **kwargs)
80
+ cache_slot.value = result
81
+ return result
77
82
 
78
83
  return cast(F, wrapped_function)
79
84
 
80
85
  if function is not None:
81
86
  cache_decorator = cache_decorator(function)
82
87
  return cache_decorator
83
-
84
-
85
- def extract_argument_values(
86
- function: F,
87
- args: tuple[Any, ...],
88
- kwargs: dict[str, Any],
89
- cache_key_arguments: tuple[str, ...] | str | None = None,
90
- ) -> Iterator[Any]:
91
- if cache_key_arguments is None:
92
- yield from (args, kwargs)
93
- else:
94
- arguments = inspect.signature(function).bind(*args, **kwargs)
95
- arguments.apply_defaults()
96
- if isinstance(cache_key_arguments, str):
97
- yield arguments.arguments.get(cache_key_arguments)
98
- else:
99
- for name in cache_key_arguments:
100
- yield arguments.arguments.get(name)
101
-
102
-
103
- def extract_reducer(
104
- reducer: type[Reducer] | None,
105
- *,
106
- deep_learning: bool,
107
- speedup_deep_learning: bool,
108
- ) -> type[Reducer]:
109
- if reducer is None:
110
- if deep_learning:
111
- from persistent_cache.reducers.deep_learning import Reducer as Reducer_
112
-
113
- reducer = Reducer_
114
- elif speedup_deep_learning:
115
- from persistent_cache.reducers.speedup_deep_learning import (
116
- Reducer as Reducer_,
117
- )
118
-
119
- reducer = Reducer_
120
- else:
121
- reducer = Reducer
122
- return reducer
@@ -54,7 +54,7 @@ class HashPickler(pickle.Pickler):
54
54
  reduction = NotImplemented
55
55
  else:
56
56
  mapping = reducer(obj)
57
- str_mapping = str(object_to_bytes(self.reducer, mapping))
57
+ str_mapping = str(item_to_bytes(self.reducer, mapping))
58
58
  reduction = str, (str_mapping,)
59
59
  return reduction
60
60
 
@@ -65,15 +65,16 @@ class HashPickler(pickle.Pickler):
65
65
  yield reducer
66
66
 
67
67
 
68
- def compute_hash(key_reducer: type[Reducer], *args: Any) -> str:
69
- data = object_to_bytes(key_reducer, args)
68
+ def compute_hash(key_reducer: type[Reducer], items: Iterator[Any]) -> str:
69
+ data = item_to_bytes(key_reducer, tuple(items))
70
70
  # use fast hash function because it is not used for security
71
71
  return hashlib.new("sha1", data=data, usedforsecurity=False).hexdigest()
72
72
 
73
73
 
74
- def object_to_bytes(key_reducer: type[Reducer], args: Any) -> bytes:
74
+ def item_to_bytes(key_reducer: type[Reducer], item: Any) -> bytes:
75
75
  with io.BytesIO() as fp:
76
76
  # Use custom pickler to generate bytes from complex structures
77
- HashPickler(fp, key_reducer).dump(args)
77
+ pickler = HashPickler(fp, key_reducer)
78
+ pickler.dump(item)
78
79
  fp.seek(0)
79
80
  return fp.read()
@@ -1,2 +1 @@
1
- from .function import F
2
1
  from .path import Path
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: persistent-function-cache
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Persistent cache for expensive functions
5
5
  Author-email: Quinten Roets <qdr2104@columbia.edu>
6
6
  License: MIT
@@ -6,19 +6,18 @@ persistent_cache/caches/speedup_deep_learning.py,sha256=bywNXeEZsg8Rs2A1_w-ZrJi9
6
6
  persistent_cache/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
7
  persistent_cache/cli/clear_cache.py,sha256=YbKfqzUB9IyEpU-2n0h5BrK9kZKjbayqiMTzjPbDl3s,1541
8
8
  persistent_cache/main/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
- persistent_cache/main/cacheslot.py,sha256=6jNF6B1aEW185aPJ7Wd7tzLIOcwqyNr2p9tkxUHhk5E,1217
10
- persistent_cache/main/decorator.py,sha256=ojMDckrv5Fwhh8RvUCeZwQl06I1Q61olvs1HSz-jtVY,3457
11
- persistent_cache/main/hashing.py,sha256=YP_HO9nJe2_ZkiQf-unM6W9y_k5TJW1JvWeZfPIXtug,2650
12
- persistent_cache/models/__init__.py,sha256=No2WagrzFJdeQE3hTIeFd2H8hhvvAFcdVH6z07D1vmI,47
13
- persistent_cache/models/function.py,sha256=C1w0rVOhUkqvpPkXNj85rc4GSJDqT0oIZLsZvhVwn58,113
9
+ persistent_cache/main/cache_slot.py,sha256=9zBrcTGJ-oEUryftiGqBks_mdrkX2s_c0b2Pisc5vvU,2716
10
+ persistent_cache/main/decorator.py,sha256=tvrgv_lTxldgxfWnvzJKvDC00oE8eenPY5VdPZxiywM,2439
11
+ persistent_cache/main/hashing.py,sha256=6GYzUJcqjfjHPWMqPOCEY9FUSH2k2zUGrUza2fKaMTQ,2688
12
+ persistent_cache/models/__init__.py,sha256=1OeLZ6FZ5gAjlerAjc69Vx0AqWLSx6OSqNCpuzkCZQg,23
14
13
  persistent_cache/models/path.py,sha256=-HRJ4yqqmBPlax4H0KS8guhndBXNwCnl7WZXhtaWmGQ,441
15
14
  persistent_cache/reducers/__init__.py,sha256=hCozFuvrAb_gXLcqMMq92v4KdwBbQugwGwCmyLGt5RE,26
16
15
  persistent_cache/reducers/base.py,sha256=HsodcuE8Id5oV93_b_RN18I69UWsJ21yazXCwT1f6YU,1428
17
16
  persistent_cache/reducers/deep_learning.py,sha256=cyVolwmwm_ZN2gRxPtfJFqiNQlNuq_CrehO7ZSVWeVw,800
18
17
  persistent_cache/reducers/speedup_deep_learning.py,sha256=kMkr1467zUsQUPOi_N8tWKWAtKUcFgsk3rh94QhETg0,1970
19
- persistent_function_cache-0.2.0.dist-info/LICENSE,sha256=ENpNaBSvIV7ifD7iNz_-lBhImbiYowqPzBc5V5R8IhM,1070
20
- persistent_function_cache-0.2.0.dist-info/METADATA,sha256=thXWcG0Xy3rs1wV86vs7GcRcIYL8c_zAdwLitFoknNs,2164
21
- persistent_function_cache-0.2.0.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
22
- persistent_function_cache-0.2.0.dist-info/entry_points.txt,sha256=fSZfuL6Wn42mZldojgGyg7dzSPCRVAuZox3w6dLd2ZI,88
23
- persistent_function_cache-0.2.0.dist-info/top_level.txt,sha256=Jj-Z9wxHRlRyDUxrfC9GeaV5-8hAf8R4LclQFZesxi8,17
24
- persistent_function_cache-0.2.0.dist-info/RECORD,,
18
+ persistent_function_cache-0.2.1.dist-info/LICENSE,sha256=ENpNaBSvIV7ifD7iNz_-lBhImbiYowqPzBc5V5R8IhM,1070
19
+ persistent_function_cache-0.2.1.dist-info/METADATA,sha256=E_GxkYLEh9vSXGpVYv9cKAMDTjqHRJDZc6d44WcqQXs,2164
20
+ persistent_function_cache-0.2.1.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
21
+ persistent_function_cache-0.2.1.dist-info/entry_points.txt,sha256=fSZfuL6Wn42mZldojgGyg7dzSPCRVAuZox3w6dLd2ZI,88
22
+ persistent_function_cache-0.2.1.dist-info/top_level.txt,sha256=Jj-Z9wxHRlRyDUxrfC9GeaV5-8hAf8R4LclQFZesxi8,17
23
+ persistent_function_cache-0.2.1.dist-info/RECORD,,
@@ -1,42 +0,0 @@
1
- import pickle
2
- from collections.abc import Callable
3
- from typing import Any, Generic, TypeVar, cast
4
-
5
- from persistent_cache.models import Path
6
- from persistent_cache.reducers.base import Reducer
7
-
8
- from . import hashing
9
-
10
- T = TypeVar("T")
11
-
12
-
13
- class CacheSlot(Generic[T]):
14
- def __init__(
15
- self,
16
- function: Callable[..., T],
17
- args: tuple[Any, ...],
18
- key_reducer: type[Reducer] = Reducer,
19
- cache_path: Path = Path.cache,
20
- ) -> None:
21
- # change cache key when implementation changes
22
- cache_keys = (function, args)
23
- self.location = (
24
- cache_path
25
- / function.__module__.replace(".", "_")
26
- / function.__name__
27
- / hashing.compute_hash(key_reducer, cache_keys)
28
- )
29
-
30
- @property
31
- def value(self) -> T:
32
- try:
33
- with self.location.open("rb") as fp:
34
- value = pickle.Unpickler(fp).load() # noqa: S301
35
- except (pickle.UnpicklingError, EOFError):
36
- # discard values of corrupted or empty slots
37
- raise KeyError from None
38
- return cast(T, value)
39
-
40
- @value.setter
41
- def value(self, value: T) -> None:
42
- self.location.byte_content = pickle.dumps(value)
@@ -1,4 +0,0 @@
1
- from collections.abc import Callable
2
- from typing import Any, TypeVar
3
-
4
- F = TypeVar("F", bound=Callable[..., Any])