dependency-cache 0.1.0__tar.gz → 0.1.2__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.0 → dependency_cache-0.1.2}/.github/workflows/Test.yml +2 -0
  2. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/Cargo.lock +62 -0
  3. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/Cargo.toml +3 -0
  4. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/PKG-INFO +13 -6
  5. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/README.md +11 -4
  6. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/pyproject.toml +2 -2
  7. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/python/dependency_cache/dependency_cache.pyi +4 -0
  8. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/python/test_python.py +47 -10
  9. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/python/test_python_automagic.py +9 -9
  10. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/src/decorator.rs +3 -2
  11. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/src/decorator_factory.rs +21 -36
  12. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/src/dependency_cache_base.rs +68 -5
  13. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/src/lib.rs +1 -1
  14. dependency_cache-0.1.2/src/py_introspection_utils.rs +113 -0
  15. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/uv.lock +1 -1
  16. dependency_cache-0.1.0/src/normalise_method_args.rs +0 -62
  17. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/.github/workflows/CI.yml +0 -0
  18. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/.gitignore +0 -0
  19. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/LICENSE +0 -0
  20. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/python/dependency_cache/__init__.py +0 -0
  21. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/python/dependency_cache/plot_dependency_graph.py +0 -0
  22. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/python/examples/automagic_dependency_example.py +0 -0
  23. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/python/examples/example.py +0 -0
  24. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/python/examples/function_calls_example.py +0 -0
  25. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/python/examples/inheritance_example.py +0 -0
  26. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/python/examples/manual_dependency_example.py +0 -0
  27. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/python/examples/use_cache_example.py +0 -0
  28. {dependency_cache-0.1.0 → dependency_cache-0.1.2}/src/dependency_graph.rs +0 -0
@@ -5,6 +5,7 @@ on:
5
5
  branches: [ "master" ]
6
6
  pull_request:
7
7
  branches: [ "master" ]
8
+ types: [ opened, synchronize, reopened, ready_for_review ]
8
9
 
9
10
  env:
10
11
  CARGO_TERM_COLOR: always
@@ -12,6 +13,7 @@ env:
12
13
  jobs:
13
14
  build:
14
15
  runs-on: ubuntu-latest
16
+ if: github.event_name != 'pull_request' || github.event.pull_request.draft == false
15
17
 
16
18
  steps:
17
19
  - uses: actions/checkout@v4
@@ -2,11 +2,50 @@
2
2
  # It is not intended for manual editing.
3
3
  version = 4
4
4
 
5
+ [[package]]
6
+ name = "cfg-if"
7
+ version = "1.0.4"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
10
+
11
+ [[package]]
12
+ name = "chacha20"
13
+ version = "0.10.2"
14
+ source = "registry+https://github.com/rust-lang/crates.io-index"
15
+ checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
16
+ dependencies = [
17
+ "cfg-if",
18
+ "cpufeatures",
19
+ "rand_core",
20
+ ]
21
+
22
+ [[package]]
23
+ name = "cpufeatures"
24
+ version = "0.3.1"
25
+ source = "registry+https://github.com/rust-lang/crates.io-index"
26
+ checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
27
+ dependencies = [
28
+ "libc",
29
+ ]
30
+
5
31
  [[package]]
6
32
  name = "dependency_cache"
7
33
  version = "0.1.0"
8
34
  dependencies = [
9
35
  "pyo3",
36
+ "rand",
37
+ ]
38
+
39
+ [[package]]
40
+ name = "getrandom"
41
+ version = "0.4.3"
42
+ source = "registry+https://github.com/rust-lang/crates.io-index"
43
+ checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
44
+ dependencies = [
45
+ "cfg-if",
46
+ "libc",
47
+ "r-efi",
48
+ "rand_core",
10
49
  ]
11
50
 
12
51
  [[package]]
@@ -108,6 +147,29 @@ dependencies = [
108
147
  "proc-macro2",
109
148
  ]
110
149
 
150
+ [[package]]
151
+ name = "r-efi"
152
+ version = "6.0.0"
153
+ source = "registry+https://github.com/rust-lang/crates.io-index"
154
+ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
155
+
156
+ [[package]]
157
+ name = "rand"
158
+ version = "0.10.2"
159
+ source = "registry+https://github.com/rust-lang/crates.io-index"
160
+ checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
161
+ dependencies = [
162
+ "chacha20",
163
+ "getrandom",
164
+ "rand_core",
165
+ ]
166
+
167
+ [[package]]
168
+ name = "rand_core"
169
+ version = "0.10.1"
170
+ source = "registry+https://github.com/rust-lang/crates.io-index"
171
+ checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
172
+
111
173
  [[package]]
112
174
  name = "syn"
113
175
  version = "2.0.119"
@@ -9,6 +9,9 @@ readme = "README.md"
9
9
  name = "dependency_cache"
10
10
  crate-type = ["cdylib"]
11
11
 
12
+ [dependencies]
13
+ rand = "0.10.2"
14
+
12
15
  [dependencies.pyo3]
13
16
  version = "0.29.*"
14
17
  features = [
@@ -1,13 +1,13 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dependency_cache
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
7
7
  Requires-Dist: matplotlib>=3.7.5
8
8
  Requires-Dist: networkx>=3.1
9
9
  License-File: LICENSE
10
- Summary: A caching system with a dependency graph for invalidation
10
+ Summary: A caching library for Python object methods that utilises a dependency graph to track relationships and control invalidation, enabling efficient recomputation
11
11
  Keywords: caching,dependency-graph,invalidation
12
12
  License: MIT
13
13
  Requires-Python: >=3.8
@@ -24,13 +24,21 @@ A library for managing the caching of an object's methods with cache invalidatio
24
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
25
  This project is written in rust, with [pyo3](https://github.com/PyO3/pyo3), and compiled using [maturin](https://github.com/PyO3/maturin).
26
26
 
27
+ ### Installation
28
+
29
+ Install the latest stable version from [PyPI](https://pypi.org/project/dependency-cache/):
30
+
31
+ ```bash
32
+ pip install dependency-cache
33
+ ```
34
+
27
35
  ### API Overview
28
36
 
29
37
  | Export | What it's for |
30
38
  |---|---|
31
39
  | `DependencyCacheBase` | Base class to inherit from. Gives your instance a cache and a dependency graph. |
32
- | `dependency_cached(use_cache=True, dependencies=[...], track_runtime_dependencies=False)` | A footgun-enabled :gun: decorator for a method where you **explicitly declare** direct dependencies. |
33
- | `automagically_dependency_cached(use_cache=True, dependencies=[...], track_runtime_dependencies=True)` | A decorator which **automagically infers** the direct dependencies with the option to override manually using `dependencies=`. |
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. |
34
42
  | `plot_dependency_graph(obj, **kwargs)` | Visualizes an instance's dependency graph, for inspection/debugging. |
35
43
 
36
44
  ### Setup
@@ -110,8 +118,7 @@ uv run ./python/examples/example.py
110
118
  This project is still a work in progress, with everything from API to underlying design subject to change on my whim.
111
119
 
112
120
  Current TODO list (in no particular order):
113
- - load and dump cache methods for base class
114
- - add back in ast parsing
121
+ - add back in ast parsing, to decorator factory
115
122
  - move plot_dependency_graph to rust side instead of python
116
123
  - add object thread safety for python 3.14+
117
124
  - work out how best to handle nested objects
@@ -6,13 +6,21 @@ A library for managing the caching of an object's methods with cache invalidatio
6
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
7
  This project is written in rust, with [pyo3](https://github.com/PyO3/pyo3), and compiled using [maturin](https://github.com/PyO3/maturin).
8
8
 
9
+ ### Installation
10
+
11
+ Install the latest stable version from [PyPI](https://pypi.org/project/dependency-cache/):
12
+
13
+ ```bash
14
+ pip install dependency-cache
15
+ ```
16
+
9
17
  ### API Overview
10
18
 
11
19
  | Export | What it's for |
12
20
  |---|---|
13
21
  | `DependencyCacheBase` | Base class to inherit from. Gives your instance a cache and a dependency graph. |
14
- | `dependency_cached(use_cache=True, dependencies=[...], track_runtime_dependencies=False)` | A footgun-enabled :gun: decorator for a method where you **explicitly declare** direct dependencies. |
15
- | `automagically_dependency_cached(use_cache=True, dependencies=[...], track_runtime_dependencies=True)` | A decorator which **automagically infers** the direct dependencies with the option to override manually using `dependencies=`. |
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. |
16
24
  | `plot_dependency_graph(obj, **kwargs)` | Visualizes an instance's dependency graph, for inspection/debugging. |
17
25
 
18
26
  ### Setup
@@ -92,8 +100,7 @@ uv run ./python/examples/example.py
92
100
  This project is still a work in progress, with everything from API to underlying design subject to change on my whim.
93
101
 
94
102
  Current TODO list (in no particular order):
95
- - load and dump cache methods for base class
96
- - add back in ast parsing
103
+ - add back in ast parsing, to decorator factory
97
104
  - move plot_dependency_graph to rust side instead of python
98
105
  - add object thread safety for python 3.14+
99
106
  - work out how best to handle nested objects
@@ -11,8 +11,8 @@ classifiers = [
11
11
  "Programming Language :: Python :: Implementation :: PyPy",
12
12
  ]
13
13
  keywords = ["caching", "dependency-graph", "invalidation"]
14
- version = "0.1.0"
15
- description = "A caching system with a dependency graph for invalidation"
14
+ version = "0.1.2"
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" }
18
18
  dependencies = [
@@ -3,11 +3,13 @@ from typing import Any, final
3
3
  class DependencyCacheBase:
4
4
  def __new__(cls, /, *_args, **_kwargs) -> DependencyCacheBase: ...
5
5
  def clear_cache(self, /) -> None: ...
6
+ def dump_cache(self, /) -> dict: ...
6
7
  def get_cached_value(self, /, method_name: str, **kwargs) -> Any | None: ...
7
8
  def get_cached_value_by_hash(self, /, hash: int) -> Any | None: ...
8
9
  def get_cached_values(self, /) -> dict: ...
9
10
  def get_dependency_graph(self, /) -> dict: ...
10
11
  def get_validation_state(self, /) -> dict: ...
12
+ def load_cache(self, /, data: dict) -> None: ...
11
13
  def update_cached_value(
12
14
  self, /, method_name: str, value: Any, **kwargs
13
15
  ) -> None: ...
@@ -21,6 +23,7 @@ class automagically_dependency_cached:
21
23
  use_cache: bool = True,
22
24
  dependencies: Any | None = None,
23
25
  track_runtime_dependencies: bool = True,
26
+ serialisable: bool = False,
24
27
  ) -> automagically_dependency_cached: ...
25
28
 
26
29
  @final
@@ -32,4 +35,5 @@ class dependency_cached:
32
35
  use_cache: bool = True,
33
36
  dependencies: Any | None = None,
34
37
  track_runtime_dependencies: bool = False,
38
+ serialisable: bool = False,
35
39
  ) -> dependency_cached: ...
@@ -11,15 +11,6 @@ class IncorrectInheritance:
11
11
  return 1
12
12
 
13
13
 
14
- class IncorrectMethod(DependencyCacheBase):
15
- def __init__(self):
16
- super().__init__()
17
-
18
- @dependency_cached()
19
- def A():
20
- return 1
21
-
22
-
23
14
  class SimpleTestObj(DependencyCacheBase):
24
15
  def __init__(self, x, y):
25
16
  super().__init__()
@@ -130,14 +121,41 @@ class FunctionCallObj(DependencyCacheBase):
130
121
  return total
131
122
 
132
123
 
124
+ class SerialisableObj(DependencyCacheBase):
125
+ @dependency_cached(serialisable=True)
126
+ def A(self):
127
+ return None
128
+
129
+ @dependency_cached(serialisable=True)
130
+ def B(self):
131
+ return None
132
+
133
+ @dependency_cached(dependencies=["A", "B"])
134
+ def C(self):
135
+ a = self.A()
136
+ b = self.B()
137
+ if a and b:
138
+ return a + b
139
+ return None
140
+
141
+
133
142
  def test_raises_typeerror():
134
- c = IncorrectInheritance()
135
143
  with pytest.raises(TypeError):
144
+ c = IncorrectInheritance()
136
145
  c.A()
137
146
 
138
147
 
139
148
  def test_incorrect_method_raises_valueerror():
140
149
  with pytest.raises(TypeError):
150
+
151
+ class IncorrectMethod(DependencyCacheBase):
152
+ def __init__(self):
153
+ super().__init__()
154
+
155
+ @dependency_cached()
156
+ def A():
157
+ return 1
158
+
141
159
  c = IncorrectMethod()
142
160
  c.A()
143
161
 
@@ -308,3 +326,22 @@ def test_incorrect_decorator_format():
308
326
  @dependency_cached()
309
327
  def B(self):
310
328
  return 2
329
+
330
+
331
+ @pytest.mark.parametrize(
332
+ ("data", "result"),
333
+ [
334
+ ({"A": 1, "B": 2}, 3),
335
+ ({"A": 1.45, "B": 2.55}, 4.0),
336
+ ({"A": "1", "B": "2"}, "12"),
337
+ ({"A": [1], "B": [2]}, [1, 2]),
338
+ ],
339
+ )
340
+ def test_serialising_data(data, result):
341
+ obj = SerialisableObj()
342
+
343
+ obj.load_cache(data)
344
+
345
+ assert obj.C() is not None
346
+
347
+ assert obj.C() == result
@@ -11,15 +11,6 @@ class IncorrectInheritance:
11
11
  return 1
12
12
 
13
13
 
14
- class IncorrectMethod(DependencyCacheBase):
15
- def __init__(self):
16
- super().__init__()
17
-
18
- @automagically_dependency_cached()
19
- def A():
20
- return 1
21
-
22
-
23
14
  class SimpleTestObj(DependencyCacheBase):
24
15
  def __init__(self, x, y):
25
16
  super().__init__()
@@ -138,6 +129,15 @@ def test_raises_typeerror():
138
129
 
139
130
  def test_incorrect_method_raises_valueerror():
140
131
  with pytest.raises(TypeError):
132
+
133
+ class IncorrectMethod(DependencyCacheBase):
134
+ def __init__(self):
135
+ super().__init__()
136
+
137
+ @automagically_dependency_cached()
138
+ def A():
139
+ return 1
140
+
141
141
  c = IncorrectMethod()
142
142
  c.A()
143
143
 
@@ -3,7 +3,7 @@ use pyo3::prelude::*;
3
3
  use pyo3::types::{PyDict, PyTuple};
4
4
 
5
5
  use crate::dependency_cache_base::DependencyCacheBase;
6
- use crate::normalise_method_args::normalise_and_hash_method;
6
+ use crate::py_introspection_utils::normalise_function_signature_and_hash;
7
7
 
8
8
  #[pyclass(frozen)]
9
9
  pub struct DependencyCacheDecorator {
@@ -12,6 +12,7 @@ pub struct DependencyCacheDecorator {
12
12
  pub dependencies: Vec<isize>,
13
13
  pub method_name: String,
14
14
  pub track_runtime_dependencies: bool,
15
+ pub serialisable: bool,
15
16
  }
16
17
 
17
18
  #[pymethods]
@@ -61,7 +62,7 @@ impl DependencyCacheDecorator {
61
62
  })?;
62
63
 
63
64
  let func = self.func.bind(py);
64
- let (hash, metadata) = normalise_and_hash_method(py, &self.method_name, Some(func), args, kwargs)?;
65
+ let (hash, metadata) = normalise_function_signature_and_hash(py, &self.method_name, Some(func), args, kwargs)?;
65
66
 
66
67
  // 1. add/check child dependencies
67
68
  base.borrow_mut().add_children_dependencies(hash, self.dependencies.clone(), metadata.unbind());
@@ -1,56 +1,29 @@
1
1
  use pyo3::prelude::*;
2
- use pyo3::types::{PyDict, PyList, PyTuple};
3
- use pyo3::exceptions::PyValueError;
2
+ use pyo3::types::{PyDict, PyTuple};
4
3
 
5
4
  use crate::decorator::DependencyCacheDecorator;
6
- use crate::normalise_method_args::normalise_and_hash_method;
5
+ use crate::py_introspection_utils::{normalise_function_signature_and_hash, parse_dependencies, validate_self_only_method};
7
6
 
8
7
 
9
- fn parse_dependencies(py: Python<'_>, dep_list: &Bound<'_, PyAny>) -> PyResult<Vec<(String, Py<PyDict>)>> {
10
- let list = dep_list.cast::<PyList>()?;
11
- let mut parsed = Vec::with_capacity(list.len());
12
-
13
- for item in list.iter() {
14
- if let Ok(tuple) = item.cast::<PyTuple>() {
15
- if tuple.len() == 2 {
16
- let method_name: String = tuple.get_item(0)?.extract()?;
17
- let kwargs = tuple.get_item(1)?;
18
- let kwargs_dict = kwargs.cast::<PyDict>()?;
19
- parsed.push((method_name, kwargs_dict.clone().unbind()));
20
- continue;
21
- }
22
- }
23
-
24
- if let Ok(method_name) = item.extract::<String>() {
25
- let empty_dict = PyDict::new(py);
26
- parsed.push((method_name, empty_dict.unbind()));
27
- continue;
28
- }
29
-
30
- return Err(PyValueError::new_err(
31
- "Dependency must be a tuple (str, dict) or a str",
32
- ));
33
- }
34
-
35
- return Ok(parsed);
36
- }
37
-
38
8
  #[pyclass(name = "dependency_cached", frozen)]
39
9
  pub struct ManualDependencyCacheDecoratorFactory {
40
10
  use_cache: bool,
41
11
  dependencies: Vec<(String, Py<PyDict>)>,
42
12
  track_runtime_dependencies: bool,
13
+ serialisable: bool,
43
14
  }
44
15
 
45
16
  #[pymethods]
46
17
  impl ManualDependencyCacheDecoratorFactory {
18
+
47
19
  #[new]
48
- #[pyo3(signature = (use_cache=true, dependencies=None, track_runtime_dependencies=false))]
20
+ #[pyo3(signature = (use_cache=true, dependencies=None, track_runtime_dependencies=false, serialisable=false))]
49
21
  fn new(
50
22
  py: Python<'_>,
51
23
  use_cache: bool,
52
24
  dependencies: Option<&Bound<'_, PyAny>>,
53
25
  track_runtime_dependencies: bool,
26
+ serialisable: bool,
54
27
  ) -> PyResult<Self> {
55
28
  let parsed_deps = if let Some(list) = dependencies {
56
29
  parse_dependencies(py, list)?
@@ -61,6 +34,7 @@ impl ManualDependencyCacheDecoratorFactory {
61
34
  use_cache,
62
35
  dependencies: parsed_deps,
63
36
  track_runtime_dependencies,
37
+ serialisable,
64
38
  });
65
39
  }
66
40
 
@@ -71,7 +45,7 @@ impl ManualDependencyCacheDecoratorFactory {
71
45
  .dependencies
72
46
  .iter()
73
47
  .map(|(method_name, kwargs)| {
74
- let (hash, _) = normalise_and_hash_method(
48
+ let (hash, _) = normalise_function_signature_and_hash(
75
49
  py,
76
50
  method_name,
77
51
  None,
@@ -81,12 +55,16 @@ impl ManualDependencyCacheDecoratorFactory {
81
55
  Ok(hash)
82
56
  })
83
57
  .collect::<PyResult<Vec<_>>>()?;
58
+ if self.serialisable {
59
+ validate_self_only_method(py, func.bind(py))?;
60
+ }
84
61
  return Ok(DependencyCacheDecorator {
85
62
  func,
86
63
  use_cache: self.use_cache,
87
64
  dependencies: hashed_dependencies,
88
65
  method_name,
89
66
  track_runtime_dependencies: self.track_runtime_dependencies,
67
+ serialisable: self.serialisable,
90
68
  });
91
69
  }
92
70
  }
@@ -96,17 +74,19 @@ pub struct AutomagicDependencyCacheDecoratorFactory {
96
74
  use_cache: bool,
97
75
  dependencies: Vec<(String, Py<PyDict>)>,
98
76
  track_runtime_dependencies: bool,
77
+ serialisable: bool,
99
78
  }
100
79
 
101
80
  #[pymethods]
102
81
  impl AutomagicDependencyCacheDecoratorFactory {
103
82
  #[new]
104
- #[pyo3(signature = (use_cache=true, dependencies=None, track_runtime_dependencies=true))]
83
+ #[pyo3(signature = (use_cache=true, dependencies=None, track_runtime_dependencies=true, serialisable=false))]
105
84
  fn new(
106
85
  py: Python<'_>,
107
86
  use_cache: bool,
108
87
  dependencies: Option<&Bound<'_, PyAny>>,
109
88
  track_runtime_dependencies: bool,
89
+ serialisable: bool,
110
90
  ) -> PyResult<Self> {
111
91
  let parsed_deps = if let Some(list) = dependencies {
112
92
  parse_dependencies(py, list)?
@@ -117,6 +97,7 @@ impl AutomagicDependencyCacheDecoratorFactory {
117
97
  use_cache,
118
98
  dependencies: parsed_deps,
119
99
  track_runtime_dependencies,
100
+ serialisable,
120
101
  });
121
102
  }
122
103
 
@@ -127,7 +108,7 @@ impl AutomagicDependencyCacheDecoratorFactory {
127
108
  .dependencies
128
109
  .iter()
129
110
  .map(|(method_name, kwargs)| {
130
- let (hash, _) = normalise_and_hash_method(
111
+ let (hash, _) = normalise_function_signature_and_hash(
131
112
  py,
132
113
  method_name,
133
114
  None,
@@ -137,12 +118,16 @@ impl AutomagicDependencyCacheDecoratorFactory {
137
118
  Ok(hash)
138
119
  })
139
120
  .collect::<PyResult<Vec<_>>>()?;
121
+ if self.serialisable {
122
+ validate_self_only_method(py, func.bind(py))?;
123
+ }
140
124
  return Ok(DependencyCacheDecorator {
141
125
  func,
142
126
  use_cache: self.use_cache,
143
127
  dependencies: hashed_dependencies,
144
128
  method_name,
145
129
  track_runtime_dependencies: self.track_runtime_dependencies,
130
+ serialisable: self.serialisable,
146
131
  });
147
132
  }
148
133
  }
@@ -1,10 +1,15 @@
1
1
  use pyo3::prelude::*;
2
- use pyo3::types::{PyDict, PyTuple, PyString, PySet};
2
+ use pyo3::types::{PyDict, PyTuple, PyString, PySet, PyType};
3
+ use pyo3::exceptions::PyValueError;
3
4
 
4
- use std::collections::{HashMap};
5
+ use rand::rng;
6
+ use rand::seq::SliceRandom;
7
+
8
+ use std::collections::{HashMap, HashSet};
5
9
 
6
10
  use crate::dependency_graph::{MethodDependencyGraph, ValidationState};
7
- use crate::normalise_method_args::normalise_and_hash_method;
11
+ use crate::py_introspection_utils::normalise_function_signature_and_hash;
12
+ use crate::decorator::DependencyCacheDecorator;
8
13
 
9
14
 
10
15
  #[pyclass(subclass)]
@@ -140,6 +145,7 @@ impl DependencyCacheBase {
140
145
  // slf.borrow_mut().method_dependency_graph = graph;
141
146
  // return Ok(());
142
147
  // }
148
+
143
149
  pub fn get_cached_value_by_hash(&self, py: Python<'_>, hash: isize) -> Option<Py<PyAny>> {
144
150
  if self.method_dependency_graph.is_valid(hash) {
145
151
  return self.cache.get(&hash).map(|obj| obj.clone_ref(py));
@@ -151,7 +157,7 @@ impl DependencyCacheBase {
151
157
  pub fn get_cached_value(&self, py: Python<'_>, method_name: String, kwargs: Option<Py<PyDict>>) -> Option<Py<PyAny>> {
152
158
  let empty_args = PyTuple::empty(py);
153
159
  let kwargs_bound = kwargs.as_ref().map(|k| k.bind(py));
154
- let (hash, _) = normalise_and_hash_method(py, &method_name, None, &empty_args, kwargs_bound).ok()?;
160
+ let (hash, _) = normalise_function_signature_and_hash(py, &method_name, None, &empty_args, kwargs_bound).ok()?;
155
161
 
156
162
  if self.method_dependency_graph.is_valid(hash) {
157
163
  self.cache.get(&hash).map(|obj| obj.clone_ref(py))
@@ -164,7 +170,7 @@ impl DependencyCacheBase {
164
170
  pub fn update_cached_value(&mut self, py: Python<'_>, method_name: String, value: Py<PyAny>, kwargs: Option<Py<PyDict>>) {
165
171
  let empty_args = PyTuple::empty(py);
166
172
  let kwargs_bound = kwargs.as_ref().map(|k| k.bind(py));
167
- let Ok((hash, _)) = normalise_and_hash_method(py, &method_name, None, &empty_args, kwargs_bound) else {
173
+ let Ok((hash, _)) = normalise_function_signature_and_hash(py, &method_name, None, &empty_args, kwargs_bound) else {
168
174
  return;
169
175
  };
170
176
 
@@ -269,4 +275,61 @@ impl DependencyCacheBase {
269
275
  }
270
276
  Ok(dict)
271
277
  }
278
+
279
+ pub fn dump_cache<'py>(slf: &Bound<'py, Self>, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
280
+ let cls = slf.get_type();
281
+
282
+ let mut visited = HashSet::new();
283
+ let mut serialisable_methods = Vec::new();
284
+
285
+ for mro_class in cls.mro().iter() {
286
+ let mro_class: Bound<'_, PyType> = mro_class.extract()?;
287
+ let namespace = mro_class.getattr("__dict__")?;
288
+
289
+ // change methods to random order, since we do know what order is best
290
+ let method_names = namespace.call_method0("items")?.try_iter()?;
291
+ let mut method_names: Vec<_> = method_names.collect();
292
+ method_names.shuffle(&mut rng());
293
+
294
+ for method_name in method_names {
295
+ let (name, value): (String, Bound<'_, PyAny>) = method_name?.extract()?;
296
+ if name.starts_with("__") || !visited.insert(name.clone()) {
297
+ continue;
298
+ }
299
+ if let Ok(decorator) = value.cast::<DependencyCacheDecorator>() {
300
+ if decorator.borrow().serialisable {
301
+ serialisable_methods.push(name);
302
+ }
303
+ }
304
+ }
305
+ }
306
+
307
+ let result = PyDict::new(py);
308
+ for method_name in serialisable_methods {
309
+ let value = slf.call_method(&method_name, (), None)?;
310
+ result.set_item(method_name, value)?;
311
+ }
312
+
313
+ Ok(result)
314
+ }
315
+
316
+ pub fn load_cache<'py>(
317
+ slf: &Bound<'_, Self>,
318
+ py: Python<'py>,
319
+ data: Bound<'py, PyDict>,
320
+ ) -> PyResult<()> {
321
+ for (key, loaded_value) in data.iter() {
322
+ let method_name: String = key.extract()?;
323
+
324
+ let _ = slf.call_method(&method_name, (), None)?;
325
+
326
+ let empty_args = PyTuple::empty(py);
327
+ let (hash, _) = normalise_function_signature_and_hash(py, &method_name, None, &empty_args, None)
328
+ .map_err(|e| PyValueError::new_err(format!("Failed to hash '{}': {}", method_name, e)))?;
329
+
330
+ slf.borrow_mut().cache.insert(hash, loaded_value.unbind());
331
+ }
332
+
333
+ Ok(())
334
+ }
272
335
  }
@@ -2,7 +2,7 @@ mod decorator;
2
2
  mod dependency_graph;
3
3
  mod dependency_cache_base;
4
4
  mod decorator_factory;
5
- mod normalise_method_args;
5
+ mod py_introspection_utils;
6
6
 
7
7
  use pyo3::prelude::*;
8
8
 
@@ -0,0 +1,113 @@
1
+ use pyo3::prelude::*;
2
+ use pyo3::exceptions::PyValueError;
3
+ use pyo3::types::{PyDict, PyString, PyTuple, PyList};
4
+
5
+
6
+ pub fn normalise_function_signature_and_hash<'py>(
7
+ py: Python<'py>,
8
+ func_name: &str,
9
+ func: Option<&Bound<'py, PyAny>>,
10
+ args: &Bound<'py, PyTuple>,
11
+ kwargs: Option<&Bound<'py, PyDict>>,
12
+ ) -> PyResult<(isize, Bound<'py, PyTuple>)> {
13
+ let dict = match func {
14
+ Some(f) => {
15
+ let inspect = py.import("inspect")?;
16
+ let bound = inspect
17
+ .getattr("signature")?
18
+ .call1((f,))?
19
+ .getattr("bind")?
20
+ .call(args, kwargs)?;
21
+ bound.getattr("apply_defaults")?.call0()?;
22
+ bound.getattr("arguments")?
23
+ }
24
+ None => match kwargs {
25
+ Some(d) => d.clone().into_any(),
26
+ None => PyDict::new(py).into_any(),
27
+ },
28
+ };
29
+
30
+ let dict = dict.cast::<PyDict>()?;
31
+
32
+ let mut items: Vec<(String, Bound<'py, PyAny>)> = Vec::new();
33
+ for (k, v) in dict.iter() {
34
+ let key: String = k.extract()?;
35
+ if key == "self" {
36
+ continue;
37
+ }
38
+ items.push((key, v));
39
+ }
40
+ items.sort_by(|a, b| a.0.cmp(&b.0));
41
+
42
+
43
+ let pairs = items
44
+ .into_iter()
45
+ .map(|(k, v)| {
46
+ let k_py = PyString::new(py, &k).into_any();
47
+ PyTuple::new(py, vec![k_py, v])
48
+ })
49
+ .collect::<PyResult<Vec<_>>>()?;
50
+
51
+ let normalised = PyTuple::new(py, pairs)?;
52
+
53
+ let combined = PyTuple::new(
54
+ py,
55
+ vec![
56
+ PyString::new(py, func_name).into_any(),
57
+ normalised.clone().into_any(),
58
+ ],
59
+ )?;
60
+ let hash_val = combined.hash()?;
61
+
62
+ return Ok((hash_val, combined));
63
+ }
64
+
65
+
66
+ pub fn validate_self_only_method(py: Python<'_>, func: &Bound<'_, PyAny>) -> PyResult<()> {
67
+ let inspect = py.import("inspect")?;
68
+ let builtins = py.import("builtins")?;
69
+ let signature = inspect.call_method1("signature", (func,))?;
70
+ // really ugly, but the inspect.Signature type is not extractable
71
+ let parameters = signature.getattr("parameters")?;
72
+ let list_obj = builtins.call_method1("list", (parameters,))?;
73
+ let param_names: Vec<String> = list_obj.extract()?;
74
+
75
+ if param_names.len() != 1 || param_names[0] != "self" {
76
+ let msg = format!(
77
+ "Serialisable method must have exactly one parameter named 'self', got: {:?}",
78
+ param_names
79
+ );
80
+ return Err(PyValueError::new_err(msg));
81
+ }
82
+ Ok(())
83
+ }
84
+
85
+
86
+ pub fn parse_dependencies(py: Python<'_>, dep_list: &Bound<'_, PyAny>) -> PyResult<Vec<(String, Py<PyDict>)>> {
87
+ let list = dep_list.cast::<PyList>()?;
88
+ let mut parsed = Vec::with_capacity(list.len());
89
+
90
+ for item in list.iter() {
91
+ if let Ok(tuple) = item.cast::<PyTuple>() {
92
+ if tuple.len() == 2 {
93
+ let method_name: String = tuple.get_item(0)?.extract()?;
94
+ let kwargs = tuple.get_item(1)?;
95
+ let kwargs_dict = kwargs.cast::<PyDict>()?;
96
+ parsed.push((method_name, kwargs_dict.clone().unbind()));
97
+ continue;
98
+ }
99
+ }
100
+
101
+ if let Ok(method_name) = item.extract::<String>() {
102
+ let empty_dict = PyDict::new(py);
103
+ parsed.push((method_name, empty_dict.unbind()));
104
+ continue;
105
+ }
106
+
107
+ return Err(PyValueError::new_err(
108
+ "Dependency must be a tuple (str, dict) or a str",
109
+ ));
110
+ }
111
+
112
+ return Ok(parsed);
113
+ }
@@ -329,7 +329,7 @@ wheels = [
329
329
 
330
330
  [[package]]
331
331
  name = "dependency-cache"
332
- version = "0.1.0"
332
+ version = "0.1.2"
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'" },
@@ -1,62 +0,0 @@
1
- use pyo3::prelude::*;
2
- use pyo3::types::{PyDict, PyString, PyTuple};
3
-
4
-
5
- pub fn normalise_and_hash_method<'py>(
6
- py: Python<'py>,
7
- func_name: &str,
8
- func: Option<&Bound<'py, PyAny>>,
9
- args: &Bound<'py, PyTuple>,
10
- kwargs: Option<&Bound<'py, PyDict>>,
11
- ) -> PyResult<(isize, Bound<'py, PyTuple>)> {
12
- let dict = match func {
13
- Some(f) => {
14
- let inspect = py.import("inspect")?;
15
- let bound = inspect
16
- .getattr("signature")?
17
- .call1((f,))?
18
- .getattr("bind")?
19
- .call(args, kwargs)?;
20
- bound.getattr("apply_defaults")?.call0()?;
21
- bound.getattr("arguments")?
22
- }
23
- None => match kwargs {
24
- Some(d) => d.clone().into_any(),
25
- None => PyDict::new(py).into_any(),
26
- },
27
- };
28
-
29
- let dict = dict.cast::<PyDict>()?;
30
-
31
- let mut items: Vec<(String, Bound<'py, PyAny>)> = Vec::new();
32
- for (k, v) in dict.iter() {
33
- let key: String = k.extract()?;
34
- if key == "self" {
35
- continue;
36
- }
37
- items.push((key, v));
38
- }
39
- items.sort_by(|a, b| a.0.cmp(&b.0));
40
-
41
-
42
- let pairs = items
43
- .into_iter()
44
- .map(|(k, v)| {
45
- let k_py = PyString::new(py, &k).into_any();
46
- PyTuple::new(py, vec![k_py, v])
47
- })
48
- .collect::<PyResult<Vec<_>>>()?;
49
-
50
- let normalised = PyTuple::new(py, pairs)?;
51
-
52
- let combined = PyTuple::new(
53
- py,
54
- vec![
55
- PyString::new(py, func_name).into_any(),
56
- normalised.clone().into_any(),
57
- ],
58
- )?;
59
- let hash_val = combined.hash()?;
60
-
61
- return Ok((hash_val, combined));
62
- }