dependency-cache 0.1.4__tar.gz → 0.2.1__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 (28) hide show
  1. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/PKG-INFO +12 -12
  2. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/README.md +11 -11
  3. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/pyproject.toml +1 -1
  4. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/python/dependency_cache/dependency_cache.pyi +3 -3
  5. dependency_cache-0.2.1/python/examples/runtime_dependencies_example.py +45 -0
  6. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/src/dependency_cache_base.rs +95 -18
  7. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/src/dependency_graph.rs +8 -0
  8. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/uv.lock +1 -1
  9. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/.github/workflows/CI.yml +0 -0
  10. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/.github/workflows/Test.yml +0 -0
  11. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/.gitignore +0 -0
  12. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/Cargo.lock +0 -0
  13. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/Cargo.toml +0 -0
  14. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/LICENSE +0 -0
  15. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/python/dependency_cache/__init__.py +0 -0
  16. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/python/dependency_cache/plot_dependency_graph.py +0 -0
  17. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/python/examples/automagic_dependency_example.py +0 -0
  18. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/python/examples/example.py +0 -0
  19. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/python/examples/function_calls_example.py +0 -0
  20. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/python/examples/inheritance_example.py +0 -0
  21. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/python/examples/manual_dependency_example.py +0 -0
  22. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/python/examples/use_cache_example.py +0 -0
  23. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/python/test_python.py +0 -0
  24. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/python/test_python_automagic.py +0 -0
  25. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/src/decorator.rs +0 -0
  26. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/src/decorator_factory.rs +0 -0
  27. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/src/lib.rs +0 -0
  28. {dependency_cache-0.1.4 → dependency_cache-0.2.1}/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.1.4
3
+ Version: 0.2.1
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -17,13 +17,12 @@ Project-URL: Issues, https://github.com/XtdWt/dependency_cache/issues
17
17
  Project-URL: Repository, https://github.com/XtdWt/dependency_cache
18
18
 
19
19
  # Dependency Cache
20
- ## :construction: Work In Progress :construction:
20
+ ## 🚧 Work In Progress 🚧
21
21
 
22
22
  ### Description
23
- A library for managing the caching of an object's methods with cache invalidation handled by a dependency graph.
24
- Instead of recomputing expensive, deeply nested calculations on every call, Dependency Cache stores the result and only invalidates (and recalculates) it when one of its dependencies actually changes.
25
- This project is written in rust, with [pyo3](https://github.com/PyO3/pyo3), and compiled using [maturin](https://github.com/PyO3/maturin).
26
-
23
+ Dependency Cache is a caching layer for object methods, with invalidation driven by a dependency graph.
24
+ Rather than re-running expensive, deeply nested calculations on every call, it stores each method's result and only recomputes (and marks downstream methods for recalculation) when one of its declared dependencies actually changes.
25
+ Under the hood, this project is written in Rust using [pyo3](https://github.com/PyO3/pyo3) and built with [maturin](https://github.com/PyO3/maturin).
27
26
  ### Installation
28
27
 
29
28
  Install the latest stable version from [PyPI](https://pypi.org/project/dependency-cache/):
@@ -37,14 +36,15 @@ pip install dependency-cache
37
36
  | Export | What it's for |
38
37
  |---|---|
39
38
  | `DependencyCacheBase` | Base class to inherit from. Gives your instance a cache and a dependency graph. |
40
- | `dependency_cached(use_cache=True, dependencies=[...], track_runtime_dependencies=False)` | A footgun-enabled decorator for a method where you **explicitly declare** all direct dependencies. |
41
- | `automagically_dependency_cached(use_cache=True, dependencies=[...], track_runtime_dependencies=True)` | A decorator which **automagically infers** the direct dependencies. Optionally override the defaults and inference using the `dependencies` parameter. |
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. |
42
41
  | `plot_dependency_graph(obj, **kwargs)` | Visualizes an instance's dependency graph, for inspection/debugging. |
43
42
 
44
43
  ### Setup
45
44
  This project uses (and requires) [uv](https://github.com/astral-sh/uv) as a package manager and maturin to compile.
46
45
 
47
- Steps:
46
+ To set up a local dev environment:
47
+
48
48
  - install python dependencies
49
49
  ```bash
50
50
  uv sync
@@ -118,9 +118,9 @@ uv run ./python/examples/example.py
118
118
  This project is still a work in progress, with everything from API to underlying design subject to change on my whim.
119
119
 
120
120
  Current TODO list (in no particular order):
121
- - scenario analysis capability
122
- - allow input to control ordering for cache dump
123
- - move plot_dependency_graph to rust side instead of python
121
+ - scenario analysis capability (add temporary cache to base)
122
+ - add validation to static dependencies, ensure methods are of decorator class
123
+ - improve plot_dependency_graph (maybe to GUI?) with moveable nodes
124
124
  - add object thread safety for python 3.14+
125
125
  - work out how best to handle nested objects
126
126
 
@@ -1,11 +1,10 @@
1
1
  # Dependency Cache
2
- ## :construction: Work In Progress :construction:
2
+ ## 🚧 Work In Progress 🚧
3
3
 
4
4
  ### Description
5
- A library for managing the caching of an object's methods with cache invalidation handled by a dependency graph.
6
- Instead of recomputing expensive, deeply nested calculations on every call, Dependency Cache stores the result and only invalidates (and recalculates) it when one of its dependencies actually changes.
7
- This project is written in rust, with [pyo3](https://github.com/PyO3/pyo3), and compiled using [maturin](https://github.com/PyO3/maturin).
8
-
5
+ Dependency Cache is a caching layer for object methods, with invalidation driven by a dependency graph.
6
+ Rather than re-running expensive, deeply nested calculations on every call, it stores each method's result and only recomputes (and marks downstream methods for recalculation) when one of its declared dependencies actually changes.
7
+ Under the hood, this project is written in Rust using [pyo3](https://github.com/PyO3/pyo3) and built with [maturin](https://github.com/PyO3/maturin).
9
8
  ### Installation
10
9
 
11
10
  Install the latest stable version from [PyPI](https://pypi.org/project/dependency-cache/):
@@ -19,14 +18,15 @@ pip install dependency-cache
19
18
  | Export | What it's for |
20
19
  |---|---|
21
20
  | `DependencyCacheBase` | Base class to inherit from. Gives your instance a cache and a dependency graph. |
22
- | `dependency_cached(use_cache=True, dependencies=[...], track_runtime_dependencies=False)` | A footgun-enabled decorator for a method where you **explicitly declare** all direct dependencies. |
23
- | `automagically_dependency_cached(use_cache=True, dependencies=[...], track_runtime_dependencies=True)` | A decorator which **automagically infers** the direct dependencies. Optionally override the defaults and inference using the `dependencies` parameter. |
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. |
24
23
  | `plot_dependency_graph(obj, **kwargs)` | Visualizes an instance's dependency graph, for inspection/debugging. |
25
24
 
26
25
  ### Setup
27
26
  This project uses (and requires) [uv](https://github.com/astral-sh/uv) as a package manager and maturin to compile.
28
27
 
29
- Steps:
28
+ To set up a local dev environment:
29
+
30
30
  - install python dependencies
31
31
  ```bash
32
32
  uv sync
@@ -100,8 +100,8 @@ uv run ./python/examples/example.py
100
100
  This project is still a work in progress, with everything from API to underlying design subject to change on my whim.
101
101
 
102
102
  Current TODO list (in no particular order):
103
- - scenario analysis capability
104
- - allow input to control ordering for cache dump
105
- - move plot_dependency_graph to rust side instead of python
103
+ - scenario analysis capability (add temporary cache to base)
104
+ - add validation to static dependencies, ensure methods are of decorator class
105
+ - improve plot_dependency_graph (maybe to GUI?) with moveable nodes
106
106
  - add object thread safety for python 3.14+
107
107
  - work out how best to handle nested objects
@@ -11,7 +11,7 @@ classifiers = [
11
11
  "Programming Language :: Python :: Implementation :: PyPy",
12
12
  ]
13
13
  keywords = ["caching", "dependency-graph", "invalidation"]
14
- version = "0.1.4"
14
+ version = "0.2.1"
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,15 +1,15 @@
1
+ from collections.abc import Sequence
1
2
  from typing import Any, final
2
3
 
3
4
  class DependencyCacheBase:
4
5
  def __new__(cls, /, *_args, **_kwargs) -> DependencyCacheBase: ...
5
6
  def clear_cache(self, /) -> None: ...
6
- def dump_cache(self, /) -> dict: ...
7
+ def dump_cache(self, /, order: Sequence[str] | None = None) -> dict: ...
7
8
  def get_cached_value(self, /, method_name: str, **kwargs) -> Any | None: ...
8
- def get_cached_value_by_hash(self, /, hash: int) -> Any | None: ...
9
9
  def get_cached_values(self, /) -> dict: ...
10
10
  def get_dependency_graph(self, /) -> dict: ...
11
11
  def get_validation_state(self, /) -> dict: ...
12
- def load_cache(self, /, data: dict) -> None: ...
12
+ def load_cache(self, /, data: dict, order: Sequence[str] | None = None) -> None: ...
13
13
  def update_cached_value(
14
14
  self, /, method_name: str, value: Any, **kwargs
15
15
  ) -> None: ...
@@ -0,0 +1,45 @@
1
+ from dependency_cache import DependencyCacheBase, dependency_cached
2
+
3
+
4
+ class RuntimeGraphExample(DependencyCacheBase):
5
+ """ A
6
+ // | \\
7
+ // | \\
8
+ C B D (detached until B changes)
9
+ """
10
+
11
+ @dependency_cached(track_runtime_dependencies=True)
12
+ def A(self):
13
+ print("calculating A")
14
+ if self.B():
15
+ return self.C()
16
+ return self.D()
17
+
18
+ @dependency_cached()
19
+ def B(self):
20
+ print("calculating B")
21
+ return True
22
+
23
+ @dependency_cached()
24
+ def C(self):
25
+ print("calculating C")
26
+ return 1000
27
+
28
+ @dependency_cached()
29
+ def D(self):
30
+ print("calculating D")
31
+ return 1001
32
+
33
+
34
+ if __name__ == "__main__":
35
+ c = RuntimeGraphExample()
36
+ print(c.A()) # calculates A, prints 1000
37
+ print("graph only partially built!")
38
+
39
+ print("repeatedly updating D!")
40
+ c.update_cached_value("D", 1)
41
+ c.update_cached_value("D", 2)
42
+ c.update_cached_value("D", 3)
43
+
44
+ print(c.A()) # no calculation, returns cached 1000
45
+ print(c.get_cached_values(), c.get_dependency_graph(), c.get_validation_state())
@@ -8,7 +8,7 @@ use rand::seq::SliceRandom;
8
8
  use std::collections::{HashMap, HashSet};
9
9
 
10
10
  use crate::dependency_graph::{MethodDependencyGraph, ValidationState};
11
- use crate::py_introspection_utils::normalise_function_signature_and_hash;
11
+ use crate::py_introspection_utils::{normalise_function_signature_and_hash, validate_self_only_method};
12
12
  use crate::decorator::DependencyCacheDecorator;
13
13
 
14
14
 
@@ -82,6 +82,13 @@ impl DependencyCacheBase {
82
82
  self.method_dependency_graph
83
83
  .add_children_dependency(hash, dependency, metadata);
84
84
  }
85
+
86
+ pub fn get_cached_value_by_hash(&self, py: Python<'_>, hash: isize) -> Option<Py<PyAny>> {
87
+ if self.method_dependency_graph.is_valid(hash) {
88
+ return self.cache.get(&hash).map(|obj| obj.clone_ref(py));
89
+ }
90
+ return None;
91
+ }
85
92
  }
86
93
 
87
94
  #[pymethods]
@@ -96,13 +103,6 @@ impl DependencyCacheBase {
96
103
  };
97
104
  }
98
105
 
99
- pub fn get_cached_value_by_hash(&self, py: Python<'_>, hash: isize) -> Option<Py<PyAny>> {
100
- if self.method_dependency_graph.is_valid(hash) {
101
- return self.cache.get(&hash).map(|obj| obj.clone_ref(py));
102
- }
103
- return None;
104
- }
105
-
106
106
  #[pyo3(signature = (method_name, **kwargs))]
107
107
  pub fn get_cached_value(&self, py: Python<'_>, method_name: String, kwargs: Option<Py<PyDict>>) -> Option<Py<PyAny>> {
108
108
  let empty_args = PyTuple::empty(py);
@@ -130,6 +130,7 @@ impl DependencyCacheBase {
130
130
  }
131
131
 
132
132
  pub fn clear_cache(&mut self) {
133
+ self.method_dependency_graph.invalidate_all();
133
134
  self.cache.clear();
134
135
  }
135
136
 
@@ -226,7 +227,8 @@ impl DependencyCacheBase {
226
227
  Ok(dict)
227
228
  }
228
229
 
229
- pub fn dump_cache<'py>(slf: &Bound<'py, Self>, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
230
+ #[pyo3(signature = (order=None))]
231
+ pub fn dump_cache<'py>(slf: &Bound<'py, Self>, py: Python<'py>, order: Option<Vec<String>>) -> PyResult<Bound<'py, PyDict>> {
230
232
  let cls = slf.get_type();
231
233
 
232
234
  let mut visited = HashSet::new();
@@ -250,10 +252,24 @@ impl DependencyCacheBase {
250
252
  }
251
253
  }
252
254
 
255
+ // methods from order first
256
+ let mut ordered_methods = Vec::new();
257
+ let mut remaining: HashSet<String> = serialisable_methods.into_iter().collect();
258
+ if let Some(order_vec) = order {
259
+ let mut seen = HashSet::new();
260
+ for name in order_vec {
261
+ if seen.insert(name.clone()) && remaining.remove(&name) {
262
+ ordered_methods.push(name);
263
+ }
264
+ }
265
+ }
266
+ // randomise for the rest of the methods
267
+ let mut remaining_vec: Vec<String> = remaining.into_iter().collect();
268
+ remaining_vec.shuffle(&mut rng());
269
+ ordered_methods.extend(remaining_vec);
270
+
253
271
  let result = PyDict::new(py);
254
- // change methods to random order, since we do know what order is best
255
- serialisable_methods.shuffle(&mut rng());
256
- for method_name in serialisable_methods {
272
+ for method_name in ordered_methods {
257
273
  let value = slf.call_method(&method_name, (), None)?;
258
274
  result.set_item(method_name, value)?;
259
275
  }
@@ -261,21 +277,82 @@ impl DependencyCacheBase {
261
277
  Ok(result)
262
278
  }
263
279
 
280
+ #[pyo3(signature = (data, order=None))]
264
281
  pub fn load_cache<'py>(
265
282
  slf: &Bound<'_, Self>,
266
283
  py: Python<'py>,
267
284
  data: Bound<'py, PyDict>,
285
+ order: Option<Vec<String>>,
268
286
  ) -> PyResult<()> {
269
- for (key, loaded_value) in data.iter() {
270
- let method_name: String = key.extract()?;
287
+ let all_keys: Vec<String> = data
288
+ .keys()
289
+ .into_iter()
290
+ .map(|k| k.extract::<String>())
291
+ .collect::<PyResult<Vec<_>>>()?;
292
+
293
+ let class = slf.get_type();
294
+
295
+ let load_method = |name: &str| -> PyResult<()> {
296
+ let loaded_value = match data.get_item(name)? {
297
+ Some(val) => val,
298
+ None => return Ok(()),
299
+ };
271
300
 
272
- let _ = slf.call_method(&method_name, (), None)?;
301
+ let method_attr = class.getattr(name)?;
273
302
 
274
- let empty_args = PyTuple::empty(py);
275
- let (hash, _) = normalise_function_signature_and_hash(py, &method_name, None, &empty_args, None)
276
- .map_err(|e| PyValueError::new_err(format!("Failed to hash '{}': {}", method_name, e)))?;
303
+ let decorator = method_attr
304
+ .cast::<DependencyCacheDecorator>()
305
+ .map_err(|_| {
306
+ PyValueError::new_err(format!(
307
+ "Method '{}' is not decorated with @dependency_cached",
308
+ name
309
+ ))
310
+ })?;
311
+
312
+ let decorator_ref = decorator.borrow();
277
313
 
314
+
315
+ if !decorator_ref.serialisable {
316
+ return Err(PyValueError::new_err(format!(
317
+ "Method '{}' is not marked as serialisable",
318
+ name
319
+ )));
320
+ }
321
+
322
+ let underlying_func = decorator_ref.func.bind(py);
323
+ validate_self_only_method(py, &underlying_func)?;
324
+
325
+ let _ = slf.call_method(name, (), None)?;
326
+
327
+ let empty_args = PyTuple::empty(py);
328
+ let (hash, _) = normalise_function_signature_and_hash(py, name, None, &empty_args, None)
329
+ .map_err(|e| PyValueError::new_err(format!("Failed to hash '{}': {}", name, e)))?;
278
330
  slf.borrow_mut().cache.insert(hash, loaded_value.unbind());
331
+ Ok(())
332
+ };
333
+
334
+ let mut loaded = HashSet::new();
335
+
336
+ // methods from order first
337
+ if let Some(order_vec) = order {
338
+ for name in order_vec {
339
+ if loaded.contains(&name) {
340
+ continue;
341
+ }
342
+ load_method(&name)?;
343
+ loaded.insert(name.to_string());
344
+ }
345
+ }
346
+
347
+ let mut remaining_keys: Vec<String> = all_keys
348
+ .into_iter()
349
+ .filter(|name| !loaded.contains(name))
350
+ .collect();
351
+
352
+ // randomise for the rest of the methods
353
+ remaining_keys.shuffle(&mut rng());
354
+ for name in remaining_keys {
355
+ load_method(&name)?;
279
356
  }
280
357
 
281
358
  Ok(())
@@ -159,6 +159,14 @@ impl<T: Eq + Hash + Clone, M> MethodDependencyGraph<T, M> {
159
159
  where M: Clone {
160
160
  return self.metadata_map.clone();
161
161
  }
162
+
163
+ pub fn invalidate_all(&mut self) {
164
+ for state in self.validation_state.values_mut() {
165
+ if *state == ValidationState::Valid {
166
+ *state = ValidationState::Invalid;
167
+ }
168
+ }
169
+ }
162
170
  }
163
171
 
164
172
  #[cfg(test)]
@@ -329,7 +329,7 @@ wheels = [
329
329
 
330
330
  [[package]]
331
331
  name = "dependency-cache"
332
- version = "0.1.4"
332
+ version = "0.2.1"
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'" },