dependency-cache 0.4.2__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.2 → dependency_cache-0.5.0}/PKG-INFO +15 -12
  2. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/README.md +14 -11
  3. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/pyproject.toml +1 -1
  4. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/python/dependency_cache/__init__.py +2 -0
  5. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/python/dependency_cache/dependency_cache.pyi +3 -1
  6. {dependency_cache-0.4.2 → 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.2 → dependency_cache-0.5.0}/python/examples/example.py +3 -4
  10. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/python/examples/inheritance_example.py +4 -10
  11. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/python/examples/manual_dependency_example.py +3 -4
  12. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/python/examples/runtime_dependencies_example.py +4 -4
  13. {dependency_cache-0.4.2 → 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.2 → dependency_cache-0.5.0}/python/examples/static_function_calls_example.py +0 -1
  16. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/python/examples/use_cache_example.py +0 -3
  17. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/python/test_python.py +29 -15
  18. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/python/test_python_automagic.py +35 -16
  19. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/src/decorator.rs +10 -0
  20. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/src/decorator_factory.rs +1 -1
  21. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/src/dependency_cache_base.rs +109 -17
  22. {dependency_cache-0.4.2 → 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.2 → dependency_cache-0.5.0}/uv.lock +1 -1
  25. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/.github/workflows/CI.yml +0 -0
  26. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/.github/workflows/Test.yml +0 -0
  27. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/.gitignore +0 -0
  28. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/Cargo.lock +0 -0
  29. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/Cargo.toml +0 -0
  30. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/LICENSE +0 -0
  31. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/python/dependency_cache/plot_dependency_graph.py +0 -0
  32. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/src/dependency_graph.rs +0 -0
  33. {dependency_cache-0.4.2 → dependency_cache-0.5.0}/src/metadata_hash_manager.rs +0 -0
  34. {dependency_cache-0.4.2 → 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.2
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.2"
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
  ]
@@ -29,7 +29,7 @@ class automagically_dependency_cached:
29
29
  /,
30
30
  use_cache: bool = True,
31
31
  dependencies: Any | None = None,
32
- track_runtime_dependencies: bool = True,
32
+ track_runtime_dependencies: bool = False,
33
33
  serialisable: bool = False,
34
34
  ) -> automagically_dependency_cached: ...
35
35
 
@@ -44,3 +44,5 @@ class dependency_cached:
44
44
  track_runtime_dependencies: bool = False,
45
45
  serialisable: bool = False,
46
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()
@@ -155,9 +147,6 @@ def test_incorrect_method_raises_valueerror():
155
147
  with pytest.raises(TypeError):
156
148
 
157
149
  class IncorrectMethod(DependencyCacheBase):
158
- def __init__(self):
159
- super().__init__()
160
-
161
150
  @dependency_cached()
162
151
  def A():
163
152
  return 1
@@ -322,9 +311,6 @@ def test_incorrect_decorator_format():
322
311
  with pytest.raises(ValueError):
323
312
 
324
313
  class IncorrectDependencyType(DependencyCacheBase):
325
- def __init__(self):
326
- pass
327
-
328
314
  @dependency_cached(dependencies=[3, ("B", [1])])
329
315
  def A(self):
330
316
  return 1
@@ -373,3 +359,31 @@ def test_strict_get_raises():
373
359
  obj.get_cached_value("A")
374
360
 
375
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>,
@@ -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,17 +195,22 @@ 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
202
  #[pyo3(signature = (method_name, strict=true, **kwargs))]
126
- pub fn get_cached_value(&mut self, py: Python<'_>, method_name: String, strict: bool, kwargs: Option<Py<PyDict>>) -> PyResult<Option<Py<PyAny>>> {
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
- if let Some(obj) = self.cache.get(&key) {
131
- return Ok(Some(obj.clone_ref(py)));
132
- }
212
+ if let Some(value) = self.get_cached_value_by_key(py, key) {
213
+ return Ok(Some(value));
133
214
  }
134
215
 
135
216
  if strict {
@@ -148,47 +229,58 @@ impl DependencyCacheBase {
148
229
  kwargs: Option<Py<PyDict>>,
149
230
  ) -> PyResult<bool> {
150
231
  let key = self.get_key(py, &method_name, &kwargs)?;
151
- Ok(self.method_dependency_graph.is_valid(key) && self.cache.contains_key(&key))
232
+ return Ok(self.contains_cached_value(&key));
152
233
  }
153
234
 
154
235
 
155
236
  #[pyo3(signature = (method_name, value, **kwargs))]
156
- 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<()> {
157
244
  let key = self.get_key(py, &method_name, &kwargs)?;
158
245
 
159
- let Some(v) = self.cache.get_mut(&key) else {
246
+ if !self.contains_cached_value(&key) {
160
247
  return Err(PyKeyError::new_err(format!(
161
248
  "Cannot update cached value for '{method_name}'"
162
249
  )));
163
250
  };
164
- *v = value;
251
+ self.set_cached_value_by_key(key, value);
165
252
  self.method_dependency_graph.temporarily_invalidate(key);
166
253
  self.method_dependency_graph.validate(key);
167
254
  return Ok(());
168
255
  }
169
256
 
170
257
  pub fn clear_cache(&mut self) {
171
- self.method_dependency_graph.invalidate_all();
172
- self.cache.clear();
258
+ self.clear_effective_cache();
173
259
  }
174
260
 
175
261
  #[pyo3(signature = (method_name, **kwargs))]
176
- 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<()> {
177
268
  let key = self.get_key(py, &method_name, &kwargs)?;
178
269
 
179
- if self.cache.remove(&key).is_none() {
270
+ if self.remove_cached_value(&key).is_none() {
180
271
  return Err(PyKeyError::new_err(format!(
181
272
  "Cannot clear cached value for '{method_name}'"
182
273
  )));
183
274
  }
184
275
  self.method_dependency_graph.temporarily_invalidate(key);
185
- Ok(())
276
+ return Ok(());
186
277
  }
187
278
 
188
279
  #[getter]
189
280
  pub fn get_cached_values<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
190
281
  let dict = PyDict::new(py);
191
- for (key, value) in &self.cache {
282
+ let cache_state = self.effective_cache();
283
+ for (key, value) in &cache_state {
192
284
  let Some(bound) = self.metadata_hash_manager.get_signature(py, key) else {
193
285
  continue;
194
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.2"
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'" },