dependency-cache 0.4.1__tar.gz → 0.5.0__tar.gz

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.
Files changed (34) hide show
  1. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/PKG-INFO +15 -12
  2. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/README.md +14 -11
  3. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/pyproject.toml +1 -1
  4. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/python/dependency_cache/__init__.py +2 -0
  5. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/python/dependency_cache/dependency_cache.pyi +7 -3
  6. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/python/examples/automagic_dependency_example.py +4 -5
  7. dependency_cache-0.5.0/python/examples/custom_decorator_example.py +43 -0
  8. dependency_cache-0.5.0/python/examples/custom_scenario_example.py +49 -0
  9. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/python/examples/example.py +3 -4
  10. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/python/examples/inheritance_example.py +4 -10
  11. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/python/examples/manual_dependency_example.py +3 -4
  12. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/python/examples/runtime_dependencies_example.py +4 -4
  13. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/python/examples/runtime_function_calls_example.py +0 -3
  14. dependency_cache-0.5.0/python/examples/serialisable_example.py +31 -0
  15. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/python/examples/static_function_calls_example.py +0 -1
  16. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/python/examples/use_cache_example.py +0 -3
  17. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/python/test_python.py +57 -15
  18. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/python/test_python_automagic.py +35 -16
  19. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/src/decorator.rs +11 -0
  20. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/src/decorator_factory.rs +1 -1
  21. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/src/dependency_cache_base.rs +117 -16
  22. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/src/lib.rs +5 -0
  23. dependency_cache-0.5.0/src/scenario.rs +61 -0
  24. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/uv.lock +1 -1
  25. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/.github/workflows/CI.yml +0 -0
  26. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/.github/workflows/Test.yml +0 -0
  27. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/.gitignore +0 -0
  28. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/Cargo.lock +0 -0
  29. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/Cargo.toml +0 -0
  30. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/LICENSE +0 -0
  31. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/python/dependency_cache/plot_dependency_graph.py +0 -0
  32. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/src/dependency_graph.rs +0 -0
  33. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/src/metadata_hash_manager.rs +0 -0
  34. {dependency_cache-0.4.1 → dependency_cache-0.5.0}/src/py_introspection_utils.rs +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dependency_cache
3
- Version: 0.4.1
3
+ Version: 0.5.0
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -36,9 +36,12 @@ pip install dependency-cache
36
36
  | Export | What it's for |
37
37
  |---|---|
38
38
  | `DependencyCacheBase` | Base class to inherit from. Gives your instance a cache and a dependency graph. |
39
- | `dependency_cached(use_cache=True, dependencies=[...], track_runtime_dependencies=False, serialisable=False)` | A footgun-enabled decorator for a method where you **explicitly declare** all direct dependencies. |
40
- | `automagically_dependency_cached(use_cache=True, dependencies=[...], track_runtime_dependencies=True, serialisable=False)` | A decorator which **automagically infers** the direct dependencies. Optionally override the defaults and inference using the `dependencies` parameter. |
41
- | `plot_dependency_graph(obj, **kwargs)` | Visualizes an instance's dependency graph, for inspection/debugging. |
39
+ | `dependency_cached` | A footgun-enabled decorator for a method where you **explicitly declare** all direct dependencies. |
40
+ | `automagically_dependency_cached` | A decorator which **automagically infers** the direct dependencies. |
41
+ | `plot_dependency_graph` | Visualizes an instance's dependency graph, for inspection or debugging. |
42
+
43
+ All decorators accept optional parameters like use_cache, dependencies, track_runtime_dependencies, and serialisable. For exact signatures and types, see the
44
+ [generated stubs file](https://github.com/XtdWt/dependency_cache/blob/master/python/dependency_cache/dependency_cache.pyi).
42
45
 
43
46
  ### Setup
44
47
  This project uses (and requires) [uv](https://github.com/astral-sh/uv) as a package manager and maturin to compile.
@@ -75,12 +78,11 @@ from dependency_cache import DependencyCacheBase, automagically_dependency_cache
75
78
 
76
79
  class ExampleCalculation(DependencyCacheBase):
77
80
  """ C
78
- // \\
79
- A B
81
+ / \
82
+ A B
80
83
  """
81
84
 
82
85
  def __init__(self, x, y):
83
- super().__init__()
84
86
  self.x = x
85
87
  self.y = y
86
88
 
@@ -101,14 +103,14 @@ class ExampleCalculation(DependencyCacheBase):
101
103
 
102
104
 
103
105
  c = ExampleCalculation(3, 5)
104
- print(c.C()) # calculates A, B, C -> 8
105
- print(c.C()) # hits cache -> 8
106
+ print(f"Result of C = {c.C()}") # calculates all, prints 8
107
+ print(f"Result of C = {c.C()}") # hits cache, prints 8
106
108
 
107
- c.update_cached_value("A", 0) # invalidates C (but not B)
108
- print(c.C()) # recalculates C -> 5
109
+ c.update_cached_value("A", 0) # updates A, then invalidates C
110
+ print(f"Result of C = {c.C()}") # recalculates C returns 5
109
111
  ```
110
112
 
111
- This example can be found [here](https://github.com/XtdWt/dependency_cache/blob/master/python/examples/example.py) with more runnable examples and use cases provided in the [python/examples](https://github.com/XtdWt/dependency_cache/tree/master/python/examples) folder.
113
+ This example can be found at [python/examples/example.py](https://github.com/XtdWt/dependency_cache/blob/master/python/examples/example.py) with more runnable examples and use cases provided in the [python/examples](https://github.com/XtdWt/dependency_cache/tree/master/python/examples) folder.
112
114
 
113
115
  ```bash
114
116
  uv run ./python/examples/example.py
@@ -119,6 +121,7 @@ This project is still a work in progress, with everything from API to underlying
119
121
 
120
122
  Current TODO list (in no particular order):
121
123
  - scenario analysis capability (add temporary cache to base)
124
+ - add global_variable to link objects together
122
125
  - add validation to static dependencies, ensure methods are of decorator class (?)
123
126
  - improve plot_dependency_graph (maybe to GUI?) with interactive nodes
124
127
  - add object thread safety for python 3.14+
@@ -18,9 +18,12 @@ pip install dependency-cache
18
18
  | Export | What it's for |
19
19
  |---|---|
20
20
  | `DependencyCacheBase` | Base class to inherit from. Gives your instance a cache and a dependency graph. |
21
- | `dependency_cached(use_cache=True, dependencies=[...], track_runtime_dependencies=False, serialisable=False)` | A footgun-enabled decorator for a method where you **explicitly declare** all direct dependencies. |
22
- | `automagically_dependency_cached(use_cache=True, dependencies=[...], track_runtime_dependencies=True, serialisable=False)` | A decorator which **automagically infers** the direct dependencies. Optionally override the defaults and inference using the `dependencies` parameter. |
23
- | `plot_dependency_graph(obj, **kwargs)` | Visualizes an instance's dependency graph, for inspection/debugging. |
21
+ | `dependency_cached` | A footgun-enabled decorator for a method where you **explicitly declare** all direct dependencies. |
22
+ | `automagically_dependency_cached` | A decorator which **automagically infers** the direct dependencies. |
23
+ | `plot_dependency_graph` | Visualizes an instance's dependency graph, for inspection or debugging. |
24
+
25
+ All decorators accept optional parameters like use_cache, dependencies, track_runtime_dependencies, and serialisable. For exact signatures and types, see the
26
+ [generated stubs file](https://github.com/XtdWt/dependency_cache/blob/master/python/dependency_cache/dependency_cache.pyi).
24
27
 
25
28
  ### Setup
26
29
  This project uses (and requires) [uv](https://github.com/astral-sh/uv) as a package manager and maturin to compile.
@@ -57,12 +60,11 @@ from dependency_cache import DependencyCacheBase, automagically_dependency_cache
57
60
 
58
61
  class ExampleCalculation(DependencyCacheBase):
59
62
  """ C
60
- // \\
61
- A B
63
+ / \
64
+ A B
62
65
  """
63
66
 
64
67
  def __init__(self, x, y):
65
- super().__init__()
66
68
  self.x = x
67
69
  self.y = y
68
70
 
@@ -83,14 +85,14 @@ class ExampleCalculation(DependencyCacheBase):
83
85
 
84
86
 
85
87
  c = ExampleCalculation(3, 5)
86
- print(c.C()) # calculates A, B, C -> 8
87
- print(c.C()) # hits cache -> 8
88
+ print(f"Result of C = {c.C()}") # calculates all, prints 8
89
+ print(f"Result of C = {c.C()}") # hits cache, prints 8
88
90
 
89
- c.update_cached_value("A", 0) # invalidates C (but not B)
90
- print(c.C()) # recalculates C -> 5
91
+ c.update_cached_value("A", 0) # updates A, then invalidates C
92
+ print(f"Result of C = {c.C()}") # recalculates C returns 5
91
93
  ```
92
94
 
93
- This example can be found [here](https://github.com/XtdWt/dependency_cache/blob/master/python/examples/example.py) with more runnable examples and use cases provided in the [python/examples](https://github.com/XtdWt/dependency_cache/tree/master/python/examples) folder.
95
+ This example can be found at [python/examples/example.py](https://github.com/XtdWt/dependency_cache/blob/master/python/examples/example.py) with more runnable examples and use cases provided in the [python/examples](https://github.com/XtdWt/dependency_cache/tree/master/python/examples) folder.
94
96
 
95
97
  ```bash
96
98
  uv run ./python/examples/example.py
@@ -101,6 +103,7 @@ This project is still a work in progress, with everything from API to underlying
101
103
 
102
104
  Current TODO list (in no particular order):
103
105
  - scenario analysis capability (add temporary cache to base)
106
+ - add global_variable to link objects together
104
107
  - add validation to static dependencies, ensure methods are of decorator class (?)
105
108
  - improve plot_dependency_graph (maybe to GUI?) with interactive nodes
106
109
  - add object thread safety for python 3.14+
@@ -11,7 +11,7 @@ classifiers = [
11
11
  "Programming Language :: Python :: Implementation :: PyPy",
12
12
  ]
13
13
  keywords = ["caching", "dependency-graph", "invalidation"]
14
- version = "0.4.1"
14
+ version = "0.5.0"
15
15
  description = "A caching library for Python object methods that utilises a dependency graph to track relationships and control invalidation, enabling efficient recomputation"
16
16
  readme = "README.md"
17
17
  license = { text = "MIT" }
@@ -1,6 +1,7 @@
1
1
  from .dependency_cache import (
2
2
  DependencyCacheBase,
3
3
  automagically_dependency_cached,
4
+ custom_scenario,
4
5
  dependency_cached,
5
6
  )
6
7
  from .plot_dependency_graph import plot_dependency_graph
@@ -10,4 +11,5 @@ __all__ = [
10
11
  "DependencyCacheBase",
11
12
  "automagically_dependency_cached",
12
13
  "plot_dependency_graph",
14
+ "custom_scenario",
13
15
  ]
@@ -10,8 +10,10 @@ class DependencyCacheBase:
10
10
  @property
11
11
  def dependency_graph(self, /) -> dict: ...
12
12
  def dump_cache(self, /, order: Sequence[str] | None = None) -> dict: ...
13
- def get_cached_value(self, /, method_name: str, **kwargs) -> Any | None: ...
14
- def is_cached(self, /, method_name: str, kwargs: dict | None) -> bool: ...
13
+ def get_cached_value(
14
+ self, /, method_name: str, strict: bool = True, **kwargs
15
+ ) -> Any | None: ...
16
+ def is_cached(self, /, method_name: str, **kwargs) -> bool: ...
15
17
  def load_cache(self, /, data: dict, order: Sequence[str] | None = None) -> None: ...
16
18
  def update_cached_value(
17
19
  self, /, method_name: str, value: Any, **kwargs
@@ -27,7 +29,7 @@ class automagically_dependency_cached:
27
29
  /,
28
30
  use_cache: bool = True,
29
31
  dependencies: Any | None = None,
30
- track_runtime_dependencies: bool = True,
32
+ track_runtime_dependencies: bool = False,
31
33
  serialisable: bool = False,
32
34
  ) -> automagically_dependency_cached: ...
33
35
 
@@ -42,3 +44,5 @@ class dependency_cached:
42
44
  track_runtime_dependencies: bool = False,
43
45
  serialisable: bool = False,
44
46
  ) -> dependency_cached: ...
47
+
48
+ def custom_scenario(items: Sequence[Any]) -> Any: ...
@@ -3,14 +3,13 @@ from dependency_cache import DependencyCacheBase, automagically_dependency_cache
3
3
 
4
4
  class ExampleCalculationMagic(DependencyCacheBase):
5
5
  """ E
6
- // \\
7
- D \\
8
- // \\ \\
9
- A B C
6
+ / \
7
+ D \
8
+ / \ \
9
+ A B C
10
10
  """
11
11
 
12
12
  def __init__(self, x, y, z):
13
- super().__init__()
14
13
  self.x = x
15
14
  self.y = y
16
15
  self.z = z
@@ -0,0 +1,43 @@
1
+ import re
2
+ import inspect
3
+ import functools
4
+
5
+ from dependency_cache import DependencyCacheBase, dependency_cached
6
+
7
+
8
+ def custom_decorator(func):
9
+ code = inspect.getsource(func)
10
+ # NOTE: this regex parsing is simply an example and NOT in any way recommended
11
+ dependencies = re.findall(r'self\.([A-Za-z_]\w*)\(\)', code)
12
+ @dependency_cached(dependencies=dependencies)
13
+ @functools.wraps(func)
14
+ def wrapper(*call_args, **call_kwargs):
15
+ return func(*call_args, **call_kwargs)
16
+ return wrapper
17
+
18
+
19
+ class MultipleDecorators(DependencyCacheBase):
20
+
21
+ @dependency_cached()
22
+ def A(self):
23
+ print("calculating A")
24
+ return 1
25
+
26
+ @dependency_cached()
27
+ def B(self):
28
+ print("calculating B")
29
+ return 2
30
+
31
+ @custom_decorator
32
+ def C(self):
33
+ print("calculating C")
34
+ return self.A() + self.B()
35
+
36
+
37
+ if __name__ == '__main__':
38
+ print("Wrap the base `dependency_cached` to create custom decorators")
39
+ print("All decorators that are wrapped with dependency_cached will work together")
40
+ obj = MultipleDecorators()
41
+ print(f"Result of C = {obj.C()}") # calculates all, prints 3
42
+ obj.update_cached_value("B", 4) # updates B, then invalidates C
43
+ print(f"Result of C = {obj.C()}") # calculates all, prints 5
@@ -0,0 +1,49 @@
1
+ from dependency_cache import DependencyCacheBase, automagically_dependency_cached, custom_scenario
2
+
3
+
4
+ class ExampleCalculation(DependencyCacheBase):
5
+ """ C
6
+ // \\
7
+ A B
8
+ """
9
+
10
+ def __init__(self, x, y):
11
+ super().__init__()
12
+ self.x = x
13
+ self.y = y
14
+
15
+ @automagically_dependency_cached()
16
+ def A(self):
17
+ print("calculating A")
18
+ return self.x
19
+
20
+ @automagically_dependency_cached()
21
+ def B(self):
22
+ print("calculating B")
23
+ return self.y
24
+
25
+ @automagically_dependency_cached()
26
+ def C(self):
27
+ print("calculating C")
28
+ return self.B() + self.A()
29
+
30
+
31
+ if __name__ == "__main__":
32
+ print("example of using dependency_cache with custom scenarios, restoring state after")
33
+ print(" C")
34
+ print(" / \\")
35
+ print("A B")
36
+ c = ExampleCalculation(1, 2)
37
+
38
+ calcuations = [c]
39
+ print(f"Result of C = {c.C()}") # # calculates all, prints 3
40
+ with custom_scenario(calcuations):
41
+ c.update_cached_value("A", 100)
42
+ print(f"Result of C = {c.C()}") # recalculates C returns 102
43
+
44
+ with custom_scenario(calcuations):
45
+ c.update_cached_value("B", 200)
46
+ print(f"Result of C = {c.C()}") # recalculates C returns 300
47
+
48
+ print(f"Result of C = {c.C()}") # recalculates C returns 102
49
+ print(f"Result of C = {c.C()}") # recalculates C returns 3
@@ -3,12 +3,11 @@ from dependency_cache import DependencyCacheBase, automagically_dependency_cache
3
3
 
4
4
  class ExampleCalculation(DependencyCacheBase):
5
5
  """ C
6
- // \\
7
- A B
6
+ / \
7
+ A B
8
8
  """
9
9
 
10
10
  def __init__(self, x, y):
11
- super().__init__()
12
11
  self.x = x
13
12
  self.y = y
14
13
 
@@ -38,6 +37,6 @@ if __name__ == "__main__":
38
37
  print(f"Result of C = {c.C()}") # calculates all, prints 8
39
38
  print(f"cache={c.cached_values} graph={c.dependency_graph} validation={c.validation_state}")
40
39
  print(f"Result of C = {c.C()}") # hits cache, prints 8
41
- c.update_cached_value("A", 0) # invalidates C
40
+ c.update_cached_value("A", 0) # updates A, then invalidates C
42
41
  print(f"Result of C = {c.C()}") # recalculates C returns 5
43
42
  print(f"cache={c.cached_values} graph={c.dependency_graph} validation={c.validation_state}")
@@ -2,32 +2,26 @@ from dependency_cache import DependencyCacheBase, automagically_dependency_cache
2
2
 
3
3
 
4
4
  class ChildClass(DependencyCacheBase):
5
- def __init__(self):
6
- super().__init__()
7
-
8
5
  @automagically_dependency_cached()
9
6
  def A(self):
10
- print("Calculating A from Child")
7
+ print("calculating A from Child")
11
8
  return 1
12
9
 
13
10
  @automagically_dependency_cached()
14
11
  def B(self):
15
- print("Calculating B from Child")
12
+ print("calculating B from Child")
16
13
  return 3
17
14
 
18
15
 
19
16
  class ParentClass(ChildClass):
20
- def __init__(self):
21
- super().__init__()
22
-
23
17
  @automagically_dependency_cached()
24
18
  def A(self):
25
- print("Calculating A from Parent")
19
+ print("calculating A from Parent")
26
20
  return 2
27
21
 
28
22
  @automagically_dependency_cached()
29
23
  def B(self):
30
- print("Calculating B from Parent")
24
+ print("calculating B from Parent")
31
25
  return super().B()
32
26
 
33
27
 
@@ -3,14 +3,13 @@ from dependency_cache import DependencyCacheBase, dependency_cached
3
3
 
4
4
  class ExampleCalculationManual(DependencyCacheBase):
5
5
  """D E
6
- \\ //
6
+ \ /
7
7
  C
8
- // \\
9
- A B
8
+ / \
9
+ A B
10
10
  """
11
11
 
12
12
  def __init__(self, x, y):
13
- super().__init__()
14
13
  self.x = x
15
14
  self.y = y
16
15
 
@@ -2,10 +2,10 @@ from dependency_cache import DependencyCacheBase, dependency_cached
2
2
 
3
3
 
4
4
  class RuntimeGraphExample(DependencyCacheBase):
5
- """ A
6
- // | \\
7
- // | \\
8
- C B D (detached until B changes)
5
+ """ A
6
+ / | \
7
+ / | \
8
+ C B D (detached until B changes)
9
9
  """
10
10
 
11
11
  @dependency_cached(track_runtime_dependencies=True)
@@ -2,9 +2,6 @@ from dependency_cache import DependencyCacheBase, dependency_cached
2
2
 
3
3
 
4
4
  class FibonacciExample(DependencyCacheBase):
5
- def __init__(self):
6
- super().__init__()
7
-
8
5
  @dependency_cached(track_runtime_dependencies=True)
9
6
  def Calculate(self, n):
10
7
  print(f"calculating the {n=} fibonacci number")
@@ -0,0 +1,31 @@
1
+ from dependency_cache import DependencyCacheBase, dependency_cached
2
+
3
+
4
+ class SerialisableCalculation(DependencyCacheBase):
5
+
6
+ @dependency_cached(serialisable=True)
7
+ def A(self):
8
+ print("calculating A")
9
+ return 1
10
+
11
+ @dependency_cached(serialisable=True)
12
+ def B(self):
13
+ print("calculating B")
14
+ return 1
15
+
16
+ @dependency_cached(serialisable=True, dependencies=["A", "B"])
17
+ def C(self):
18
+ print("calculating C")
19
+ return self.A() + self.B()
20
+
21
+
22
+ if __name__ == "__main__":
23
+ obj1 = SerialisableCalculation()
24
+ print(f"Result of C = {obj1.C()}") # calculates all, prints 2
25
+
26
+ saved_state = obj1.dump_cache() # serialises the cache
27
+ print(f"{saved_state=}")
28
+
29
+ obj2 = SerialisableCalculation()
30
+ obj2.load_cache(saved_state) # deserialises the cache
31
+ print(f"Result of C = {obj2.C()}") # prints 2, cached value is reused
@@ -3,7 +3,6 @@ from dependency_cache import DependencyCacheBase, dependency_cached
3
3
 
4
4
  class FunctionCallObj(DependencyCacheBase):
5
5
  def __init__(self, x):
6
- super().__init__()
7
6
  self.x = x
8
7
 
9
8
  @dependency_cached(dependencies=["C"])
@@ -4,9 +4,6 @@ from dependency_cache import DependencyCacheBase, dependency_cached
4
4
 
5
5
 
6
6
  class UseCacheExample(DependencyCacheBase):
7
- def __init__(self):
8
- super().__init__()
9
-
10
7
  @dependency_cached(use_cache=False)
11
8
  def A(self):
12
9
  print("calculating A")
@@ -1,11 +1,8 @@
1
1
  import pytest
2
- from dependency_cache import DependencyCacheBase, dependency_cached, plot_dependency_graph
2
+ from dependency_cache import DependencyCacheBase, custom_scenario, dependency_cached, plot_dependency_graph
3
3
 
4
4
 
5
5
  class IncorrectInheritance:
6
- def __init__(self):
7
- pass
8
-
9
6
  @dependency_cached()
10
7
  def A(self):
11
8
  return 1
@@ -13,7 +10,6 @@ class IncorrectInheritance:
13
10
 
14
11
  class SimpleTestObj(DependencyCacheBase):
15
12
  def __init__(self, x, y):
16
- super().__init__()
17
13
  self.x = x
18
14
  self.y = y
19
15
 
@@ -32,7 +28,6 @@ class SimpleTestObj(DependencyCacheBase):
32
28
 
33
29
  class HardTestObj(DependencyCacheBase):
34
30
  def __init__(self, x, y):
35
- super().__init__()
36
31
  self.x = x
37
32
  self.y = y
38
33
 
@@ -59,7 +54,6 @@ class HardTestObj(DependencyCacheBase):
59
54
 
60
55
  class HarderTestObj(DependencyCacheBase):
61
56
  def __init__(self, x, y):
62
- super().__init__()
63
57
  self.x = x
64
58
  self.y = y
65
59
 
@@ -90,7 +84,6 @@ class HarderTestObj(DependencyCacheBase):
90
84
 
91
85
  class UseCacheObj(DependencyCacheBase):
92
86
  def __init__(self, x):
93
- super().__init__()
94
87
  self.x = x
95
88
 
96
89
  @dependency_cached(use_cache=False)
@@ -105,7 +98,6 @@ class UseCacheObj(DependencyCacheBase):
105
98
 
106
99
  class FunctionCallObj(DependencyCacheBase):
107
100
  def __init__(self, x):
108
- super().__init__()
109
101
  self.x = x
110
102
 
111
103
  @dependency_cached()
@@ -139,6 +131,12 @@ class SerialisableObj(DependencyCacheBase):
139
131
  return None
140
132
 
141
133
 
134
+ class NonesObj(DependencyCacheBase):
135
+ @dependency_cached()
136
+ def A(self):
137
+ return None
138
+
139
+
142
140
  def test_raises_typeerror():
143
141
  with pytest.raises(TypeError):
144
142
  c = IncorrectInheritance()
@@ -149,9 +147,6 @@ def test_incorrect_method_raises_valueerror():
149
147
  with pytest.raises(TypeError):
150
148
 
151
149
  class IncorrectMethod(DependencyCacheBase):
152
- def __init__(self):
153
- super().__init__()
154
-
155
150
  @dependency_cached()
156
151
  def A():
157
152
  return 1
@@ -316,9 +311,6 @@ def test_incorrect_decorator_format():
316
311
  with pytest.raises(ValueError):
317
312
 
318
313
  class IncorrectDependencyType(DependencyCacheBase):
319
- def __init__(self):
320
- pass
321
-
322
314
  @dependency_cached(dependencies=[3, ("B", [1])])
323
315
  def A(self):
324
316
  return 1
@@ -345,3 +337,53 @@ def test_serialising_data(data, result):
345
337
  assert obj.C() is not None
346
338
 
347
339
  assert obj.C() == result
340
+
341
+
342
+ def test_strict_get_raises():
343
+ obj = NonesObj()
344
+
345
+ with pytest.raises(KeyError):
346
+ obj.get_cached_value("A")
347
+
348
+ assert obj.A() is None
349
+
350
+ assert obj.is_cached("A") is True
351
+
352
+ assert obj.get_cached_value("A") is None
353
+
354
+ obj.clear_cached_value("A")
355
+
356
+ assert obj.is_cached("A") is False
357
+
358
+ with pytest.raises(KeyError):
359
+ obj.get_cached_value("A")
360
+
361
+ assert obj.get_cached_value("A", strict=False) is None
362
+
363
+
364
+ @pytest.mark.parametrize(
365
+ ("x", "y"),
366
+ [
367
+ (1, 2),
368
+ (100.1, 200.2),
369
+ (-55, -101),
370
+ ],
371
+ )
372
+ def test_custom_scenario(x, y):
373
+ obj = SimpleTestObj(x, y)
374
+
375
+ assert obj.C() == x + y
376
+
377
+ with custom_scenario([obj]):
378
+ obj.update_cached_value("A", x * 10)
379
+
380
+ assert obj.C() == x * 10 + y
381
+
382
+ with custom_scenario([obj]):
383
+ obj.update_cached_value("B", y + 3000)
384
+
385
+ assert obj.C() == x * 10 + (y + 3000)
386
+
387
+ assert obj.C() == x * 10 + y
388
+
389
+ assert obj.C() == x + y
@@ -1,11 +1,13 @@
1
1
  import pytest
2
- from dependency_cache import DependencyCacheBase, automagically_dependency_cached, plot_dependency_graph
2
+ from dependency_cache import (
3
+ DependencyCacheBase,
4
+ automagically_dependency_cached,
5
+ custom_scenario,
6
+ plot_dependency_graph,
7
+ )
3
8
 
4
9
 
5
10
  class IncorrectInheritance:
6
- def __init__(self):
7
- pass
8
-
9
11
  @automagically_dependency_cached()
10
12
  def A(self):
11
13
  return 1
@@ -13,7 +15,6 @@ class IncorrectInheritance:
13
15
 
14
16
  class SimpleTestObj(DependencyCacheBase):
15
17
  def __init__(self, x, y):
16
- super().__init__()
17
18
  self.x = x
18
19
  self.y = y
19
20
 
@@ -32,7 +33,6 @@ class SimpleTestObj(DependencyCacheBase):
32
33
 
33
34
  class HardTestObj(DependencyCacheBase):
34
35
  def __init__(self, x, y):
35
- super().__init__()
36
36
  self.x = x
37
37
  self.y = y
38
38
 
@@ -59,7 +59,6 @@ class HardTestObj(DependencyCacheBase):
59
59
 
60
60
  class HarderTestObj(DependencyCacheBase):
61
61
  def __init__(self, x, y):
62
- super().__init__()
63
62
  self.x = x
64
63
  self.y = y
65
64
 
@@ -90,7 +89,6 @@ class HarderTestObj(DependencyCacheBase):
90
89
 
91
90
  class UseCacheObj(DependencyCacheBase):
92
91
  def __init__(self, x):
93
- super().__init__()
94
92
  self.x = x
95
93
 
96
94
  @automagically_dependency_cached(use_cache=False)
@@ -105,7 +103,6 @@ class UseCacheObj(DependencyCacheBase):
105
103
 
106
104
  class FunctionCallObj(DependencyCacheBase):
107
105
  def __init__(self, x):
108
- super().__init__()
109
106
  self.x = x
110
107
 
111
108
  @automagically_dependency_cached()
@@ -113,7 +110,7 @@ class FunctionCallObj(DependencyCacheBase):
113
110
  print("calculating A!")
114
111
  return x + self.x
115
112
 
116
- @automagically_dependency_cached()
113
+ @automagically_dependency_cached(track_runtime_dependencies=True)
117
114
  def B(self):
118
115
  total = 0
119
116
  for i in range(2):
@@ -131,9 +128,6 @@ def test_incorrect_method_raises_valueerror():
131
128
  with pytest.raises(TypeError):
132
129
 
133
130
  class IncorrectMethod(DependencyCacheBase):
134
- def __init__(self):
135
- super().__init__()
136
-
137
131
  @automagically_dependency_cached()
138
132
  def A():
139
133
  return 1
@@ -298,9 +292,6 @@ def test_incorrect_decorator_format():
298
292
  with pytest.raises(ValueError):
299
293
 
300
294
  class IncorrectDependencyType(DependencyCacheBase):
301
- def __init__(self):
302
- pass
303
-
304
295
  @automagically_dependency_cached(dependencies=[3, ("B", [1])])
305
296
  def A(self):
306
297
  return 1
@@ -308,3 +299,31 @@ def test_incorrect_decorator_format():
308
299
  @automagically_dependency_cached()
309
300
  def B(self):
310
301
  return 2
302
+
303
+
304
+ @pytest.mark.parametrize(
305
+ ("x", "y"),
306
+ [
307
+ (1, 2),
308
+ (100.1, 200.2),
309
+ (-55, -101),
310
+ ],
311
+ )
312
+ def test_custom_scenario(x, y):
313
+ obj = SimpleTestObj(x, y)
314
+
315
+ assert obj.C() == x + y
316
+
317
+ with custom_scenario([obj]):
318
+ obj.update_cached_value("A", x * 10)
319
+
320
+ assert obj.C() == x * 10 + y
321
+
322
+ with custom_scenario([obj]):
323
+ obj.update_cached_value("B", y + 3000)
324
+
325
+ assert obj.C() == x * 10 + (y + 3000)
326
+
327
+ assert obj.C() == x * 10 + y
328
+
329
+ assert obj.C() == x + y
@@ -21,6 +21,16 @@ impl DependencyCacheDecorator {
21
21
  return Err(PyTypeError::new_err("Cannot assign to decorated method"));
22
22
  }
23
23
 
24
+ #[getter]
25
+ fn __name__(&self) -> &str {
26
+ &self.method_name
27
+ }
28
+
29
+ #[getter]
30
+ fn __qualname__(&self) -> &str {
31
+ &self.method_name
32
+ }
33
+
24
34
  fn __get__(
25
35
  slf: &Bound<'_, Self>,
26
36
  obj: Bound<'_, PyAny>,
@@ -64,6 +74,7 @@ impl DependencyCacheDecorator {
64
74
  let func = self.func.bind(py);
65
75
  let (hash, metadata) = normalise_function_signature_and_hash(py, &self.method_name, Some(func), args, kwargs)?;
66
76
 
77
+ // objects cannot pass themselves as an argument as the cache will trigger already borrowed error
67
78
  let key = base.try_borrow_mut()?.metadata_hash_manager.create_cache_key(py, hash, metadata.unbind())?;
68
79
 
69
80
  // 1. add/check child dependencies
@@ -85,7 +85,7 @@ pub struct AutomagicDependencyCacheDecoratorFactory {
85
85
  #[pymethods]
86
86
  impl AutomagicDependencyCacheDecoratorFactory {
87
87
  #[new]
88
- #[pyo3(signature = (use_cache=true, dependencies=None, track_runtime_dependencies=true, serialisable=false))]
88
+ #[pyo3(signature = (use_cache=true, dependencies=None, track_runtime_dependencies=false, serialisable=false))]
89
89
  fn new(
90
90
  py: Python<'_>,
91
91
  use_cache: bool,
@@ -1,6 +1,6 @@
1
1
  use pyo3::prelude::*;
2
2
  use pyo3::types::{PyDict, PyTuple, PyString, PySet, PyType};
3
- use pyo3::exceptions::{PyValueError, PyKeyError};
3
+ use pyo3::exceptions::{PyKeyError, PyRuntimeError, PyValueError};
4
4
 
5
5
  use rand::rng;
6
6
  use rand::seq::SliceRandom;
@@ -19,6 +19,7 @@ pub struct DependencyCacheBase {
19
19
  pub method_dependency_graph: MethodDependencyGraph<CacheKey>,
20
20
  pub metadata_hash_manager: MetadataHashManager,
21
21
  pub call_stack: Vec<(CacheKey, bool)>,
22
+ pub cache_stack: Vec<HashMap<CacheKey, Py<PyAny>>>,
22
23
  }
23
24
 
24
25
  impl DependencyCacheBase {
@@ -27,7 +28,11 @@ impl DependencyCacheBase {
27
28
  if !self.method_dependency_graph.is_valid(key) {
28
29
  return ();
29
30
  }
30
- self.cache.insert(key, value);
31
+ if let Some(top) = self.cache_stack.last_mut() {
32
+ top.insert(key, value);
33
+ } else {
34
+ self.cache.insert(key, value);
35
+ };
31
36
  }
32
37
 
33
38
  pub fn validate_current_method(&mut self, key: CacheKey, use_cache: bool) {
@@ -87,6 +92,9 @@ impl DependencyCacheBase {
87
92
 
88
93
  pub fn get_cached_value_by_key(&self, py: Python<'_>, key: CacheKey) -> Option<Py<PyAny>> {
89
94
  if self.method_dependency_graph.is_valid(key) {
95
+ if let Some(temp_cache_value) = self.get_from_temporary_cache(py, &key) {
96
+ return Some(temp_cache_value);
97
+ }
90
98
  return self.cache.get(&key).map(|obj| obj.clone_ref(py));
91
99
  }
92
100
  return None;
@@ -107,6 +115,74 @@ impl DependencyCacheBase {
107
115
  let key = self.metadata_hash_manager.get_cache_key(py, &hash, &sig);
108
116
  return key;
109
117
  }
118
+
119
+ pub fn push_cache_stack(&mut self) {
120
+ return self.cache_stack.push(HashMap::new());
121
+ }
122
+
123
+ pub fn pop_cache_stack(&mut self) -> PyResult<()> {
124
+ let cache_layer = self.cache_stack.pop().ok_or_else(|| PyRuntimeError::new_err("Attempted to remove non existant layer"))?;
125
+ for (key, _) in cache_layer {
126
+ self.method_dependency_graph.temporarily_invalidate(key);
127
+ }
128
+ return Ok(());
129
+ }
130
+
131
+ pub fn get_from_temporary_cache(&self, py: Python<'_>, key: &CacheKey) -> Option<Py<PyAny>> {
132
+ for layer in self.cache_stack.iter().rev() {
133
+ if let Some(v) = layer.get(key) {
134
+ return Some(v.clone_ref(py));
135
+ }
136
+ }
137
+ return None;
138
+ }
139
+
140
+ pub fn contains_cached_value(&self, key: &CacheKey) -> bool {
141
+ if !self.method_dependency_graph.is_valid(*key) {
142
+ return false;
143
+ }
144
+ return self.cache_stack
145
+ .iter()
146
+ .rev()
147
+ .any(|layer| layer.contains_key(key))
148
+ || self.cache.contains_key(key);
149
+ }
150
+
151
+ pub fn remove_cached_value(&mut self, key: &CacheKey) -> Option<Py<PyAny>> {
152
+ for layer in self.cache_stack.iter_mut().rev() {
153
+ if let Some(v) = layer.remove(key) {
154
+ return Some(v);
155
+ }
156
+ }
157
+ self.cache.remove(key)
158
+ }
159
+
160
+ pub fn effective_cache(&self) -> HashMap<&CacheKey, &Py<PyAny>> {
161
+ let mut merged: HashMap<&CacheKey, &Py<PyAny>> = self.cache.iter().collect();
162
+ for layer in &self.cache_stack {
163
+ for (k, v) in layer {
164
+ merged.insert(k, v);
165
+ }
166
+ }
167
+ return merged;
168
+ }
169
+
170
+ pub fn clear_effective_cache(&mut self) -> () {
171
+ if let Some(layer) = self.cache_stack.last_mut() {
172
+ let removed_keys: Vec<CacheKey> = {
173
+ let keys = layer.keys().cloned().collect();
174
+ layer.clear();
175
+ keys
176
+ };
177
+ for key in removed_keys {
178
+ self.method_dependency_graph.temporarily_invalidate(key);
179
+ }
180
+ layer.clear();
181
+ } else {
182
+ self.method_dependency_graph.invalidate_all();
183
+ self.cache.clear();
184
+ }
185
+ }
110
186
  }
111
187
 
112
188
  #[pymethods]
@@ -119,19 +195,33 @@ impl DependencyCacheBase {
119
195
  method_dependency_graph: MethodDependencyGraph::new(),
120
196
  metadata_hash_manager: MetadataHashManager::new(),
121
197
  call_stack: Vec::new(),
198
+ cache_stack: Vec::new(),
122
199
  };
123
200
  }
124
201
 
125
- #[pyo3(signature = (method_name, **kwargs))]
126
- pub fn get_cached_value(&mut self, py: Python<'_>, method_name: String, kwargs: Option<Py<PyDict>>) -> PyResult<Option<Py<PyAny>>> {
202
+ #[pyo3(signature = (method_name, strict=true, **kwargs))]
203
+ pub fn get_cached_value(
204
+ &mut self,
205
+ py: Python<'_>,
206
+ method_name: String,
207
+ strict: bool,
208
+ kwargs: Option<Py<PyDict>>,
209
+ ) -> PyResult<Option<Py<PyAny>>> {
127
210
  let key = self.get_key(py, &method_name, &kwargs)?;
128
211
 
129
- if self.method_dependency_graph.is_valid(key) {
130
- return Ok(self.cache.get(&key).map(|obj| obj.clone_ref(py)));
212
+ if let Some(value) = self.get_cached_value_by_key(py, key) {
213
+ return Ok(Some(value));
131
214
  }
215
+
216
+ if strict {
217
+ return Err(PyKeyError::new_err(format!(
218
+ "Cannot get cached value for '{method_name}'"
219
+ )));
220
+ };
132
221
  return Ok(None);
133
222
  }
134
223
 
224
+ #[pyo3(signature = (method_name, **kwargs))]
135
225
  pub fn is_cached(
136
226
  &mut self,
137
227
  py: Python<'_>,
@@ -139,47 +229,58 @@ impl DependencyCacheBase {
139
229
  kwargs: Option<Py<PyDict>>,
140
230
  ) -> PyResult<bool> {
141
231
  let key = self.get_key(py, &method_name, &kwargs)?;
142
- Ok(self.method_dependency_graph.is_valid(key) && self.cache.contains_key(&key))
232
+ return Ok(self.contains_cached_value(&key));
143
233
  }
144
234
 
145
235
 
146
236
  #[pyo3(signature = (method_name, value, **kwargs))]
147
- pub fn update_cached_value(&mut self, py: Python<'_>, method_name: String, value: Py<PyAny>, kwargs: Option<Py<PyDict>>) -> PyResult<()> {
237
+ pub fn update_cached_value(
238
+ &mut self,
239
+ py: Python<'_>,
240
+ method_name: String,
241
+ value: Py<PyAny>,
242
+ kwargs: Option<Py<PyDict>>,
243
+ ) -> PyResult<()> {
148
244
  let key = self.get_key(py, &method_name, &kwargs)?;
149
245
 
150
- let Some(v) = self.cache.get_mut(&key) else {
246
+ if !self.contains_cached_value(&key) {
151
247
  return Err(PyKeyError::new_err(format!(
152
248
  "Cannot update cached value for '{method_name}'"
153
249
  )));
154
250
  };
155
- *v = value;
251
+ self.set_cached_value_by_key(key, value);
156
252
  self.method_dependency_graph.temporarily_invalidate(key);
157
253
  self.method_dependency_graph.validate(key);
158
254
  return Ok(());
159
255
  }
160
256
 
161
257
  pub fn clear_cache(&mut self) {
162
- self.method_dependency_graph.invalidate_all();
163
- self.cache.clear();
258
+ self.clear_effective_cache();
164
259
  }
165
260
 
166
261
  #[pyo3(signature = (method_name, **kwargs))]
167
- pub fn clear_cached_value(&mut self, py: Python<'_>, method_name: String, kwargs: Option<Py<PyDict>>) -> PyResult<()> {
262
+ pub fn clear_cached_value(
263
+ &mut self,
264
+ py: Python<'_>,
265
+ method_name: String,
266
+ kwargs: Option<Py<PyDict>>,
267
+ ) -> PyResult<()> {
168
268
  let key = self.get_key(py, &method_name, &kwargs)?;
169
269
 
170
- if self.cache.remove(&key).is_none() {
270
+ if self.remove_cached_value(&key).is_none() {
171
271
  return Err(PyKeyError::new_err(format!(
172
272
  "Cannot clear cached value for '{method_name}'"
173
273
  )));
174
274
  }
175
275
  self.method_dependency_graph.temporarily_invalidate(key);
176
- Ok(())
276
+ return Ok(());
177
277
  }
178
278
 
179
279
  #[getter]
180
280
  pub fn get_cached_values<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
181
281
  let dict = PyDict::new(py);
182
- for (key, value) in &self.cache {
282
+ let cache_state = self.effective_cache();
283
+ for (key, value) in &cache_state {
183
284
  let Some(bound) = self.metadata_hash_manager.get_signature(py, key) else {
184
285
  continue;
185
286
  };
@@ -4,11 +4,13 @@ mod dependency_cache_base;
4
4
  mod decorator_factory;
5
5
  mod py_introspection_utils;
6
6
  mod metadata_hash_manager;
7
+ mod scenario;
7
8
 
8
9
  use pyo3::prelude::*;
9
10
 
10
11
  use dependency_cache_base::DependencyCacheBase;
11
12
  use decorator_factory::{ManualDependencyCacheDecoratorFactory, AutomagicDependencyCacheDecoratorFactory};
13
+ use scenario::custom_scenario;
12
14
 
13
15
 
14
16
  #[pymodule]
@@ -22,4 +24,7 @@ mod dependency_cache {
22
24
 
23
25
  #[pymodule_export]
24
26
  use super::AutomagicDependencyCacheDecoratorFactory;
27
+
28
+ #[pymodule_export]
29
+ use super::custom_scenario;
25
30
  }
@@ -0,0 +1,61 @@
1
+ use pyo3::prelude::*;
2
+ use pyo3::exceptions::PyTypeError;
3
+
4
+ use crate::DependencyCacheBase;
5
+
6
+ #[pyclass]
7
+ pub struct Scenario {
8
+ items: Vec<Py<PyAny>>,
9
+ }
10
+
11
+
12
+ #[pymethods]
13
+ impl Scenario {
14
+ fn __enter__<'py>(slf: &Bound<'py, Self>, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
15
+ {
16
+ let scenario = slf.borrow();
17
+ for item in &scenario.items {
18
+ let base = item
19
+ .bind(py)
20
+ .cast::<DependencyCacheBase>()
21
+ .map_err(|_| {
22
+ PyTypeError::new_err(
23
+ "The decorated method's class must inherit from DependencyCacheBase",
24
+ )
25
+ })?;
26
+ base.borrow_mut().push_cache_stack();
27
+ }
28
+ }
29
+ Ok(slf.clone().into_any())
30
+ }
31
+
32
+ fn __exit__<'py>(
33
+ slf: &Bound<'py, Self>,
34
+ py: Python<'py>,
35
+ _exc_type: Option<Bound<'_, PyAny>>,
36
+ _exc_value: Option<Bound<'_, PyAny>>,
37
+ _traceback: Option<Bound<'_, PyAny>>,
38
+ ) -> PyResult<bool> {
39
+ {
40
+ let scenario = slf.borrow();
41
+ for item in scenario.items.iter() {
42
+ let base = item
43
+ .bind(py)
44
+ .cast::<DependencyCacheBase>()
45
+ .map_err(|_| {
46
+ PyTypeError::new_err(
47
+ "The decorated method's class must inherit from DependencyCacheBase",
48
+ )
49
+ })?;
50
+ base.borrow_mut().pop_cache_stack()?;
51
+ }
52
+ }
53
+ Ok(false)
54
+ }
55
+ }
56
+
57
+
58
+ #[pyfunction]
59
+ pub fn custom_scenario(items: Vec<Py<PyAny>>) -> PyResult<Scenario> {
60
+ Ok(Scenario { items })
61
+ }
@@ -329,7 +329,7 @@ wheels = [
329
329
 
330
330
  [[package]]
331
331
  name = "dependency-cache"
332
- version = "0.4.1"
332
+ version = "0.5.0"
333
333
  source = { editable = "." }
334
334
  dependencies = [
335
335
  { name = "matplotlib", version = "3.7.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.9'" },