dependency-cache 0.1.2__tar.gz → 0.1.4__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 (27) hide show
  1. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/PKG-INFO +3 -2
  2. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/README.md +2 -1
  3. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/pyproject.toml +1 -1
  4. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/src/decorator_factory.rs +20 -8
  5. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/src/dependency_cache_base.rs +2 -54
  6. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/src/dependency_graph.rs +2 -1
  7. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/src/py_introspection_utils.rs +91 -0
  8. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/uv.lock +1 -1
  9. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/.github/workflows/CI.yml +0 -0
  10. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/.github/workflows/Test.yml +0 -0
  11. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/.gitignore +0 -0
  12. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/Cargo.lock +0 -0
  13. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/Cargo.toml +0 -0
  14. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/LICENSE +0 -0
  15. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/python/dependency_cache/__init__.py +0 -0
  16. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/python/dependency_cache/dependency_cache.pyi +0 -0
  17. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/python/dependency_cache/plot_dependency_graph.py +0 -0
  18. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/python/examples/automagic_dependency_example.py +0 -0
  19. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/python/examples/example.py +0 -0
  20. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/python/examples/function_calls_example.py +0 -0
  21. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/python/examples/inheritance_example.py +0 -0
  22. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/python/examples/manual_dependency_example.py +0 -0
  23. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/python/examples/use_cache_example.py +0 -0
  24. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/python/test_python.py +0 -0
  25. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/python/test_python_automagic.py +0 -0
  26. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/src/decorator.rs +0 -0
  27. {dependency_cache-0.1.2 → dependency_cache-0.1.4}/src/lib.rs +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dependency_cache
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -118,7 +118,8 @@ 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
- - add back in ast parsing, to decorator factory
121
+ - scenario analysis capability
122
+ - allow input to control ordering for cache dump
122
123
  - move plot_dependency_graph to rust side instead of python
123
124
  - add object thread safety for python 3.14+
124
125
  - work out how best to handle nested objects
@@ -100,7 +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
- - add back in ast parsing, to decorator factory
103
+ - scenario analysis capability
104
+ - allow input to control ordering for cache dump
104
105
  - move plot_dependency_graph to rust side instead of python
105
106
  - add object thread safety for python 3.14+
106
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.2"
14
+ version = "0.1.4"
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" }
@@ -2,7 +2,12 @@ use pyo3::prelude::*;
2
2
  use pyo3::types::{PyDict, PyTuple};
3
3
 
4
4
  use crate::decorator::DependencyCacheDecorator;
5
- use crate::py_introspection_utils::{normalise_function_signature_and_hash, parse_dependencies, validate_self_only_method};
5
+ use crate::py_introspection_utils::{
6
+ normalise_function_signature_and_hash,
7
+ parse_dependencies,
8
+ validate_self_only_method,
9
+ ast_inspect_method_dependencies,
10
+ };
6
11
 
7
12
 
8
13
  #[pyclass(name = "dependency_cached", frozen)]
@@ -50,7 +55,7 @@ impl ManualDependencyCacheDecoratorFactory {
50
55
  method_name,
51
56
  None,
52
57
  &empty_args,
53
- Some(&kwargs.bind(py)),
58
+ Some(kwargs.bind(py)),
54
59
  )?;
55
60
  Ok(hash)
56
61
  })
@@ -72,7 +77,7 @@ impl ManualDependencyCacheDecoratorFactory {
72
77
  #[pyclass(name = "automagically_dependency_cached", frozen)]
73
78
  pub struct AutomagicDependencyCacheDecoratorFactory {
74
79
  use_cache: bool,
75
- dependencies: Vec<(String, Py<PyDict>)>,
80
+ dependencies: Option<Vec<(String, Py<PyDict>)>>,
76
81
  track_runtime_dependencies: bool,
77
82
  serialisable: bool,
78
83
  }
@@ -89,9 +94,9 @@ impl AutomagicDependencyCacheDecoratorFactory {
89
94
  serialisable: bool,
90
95
  ) -> PyResult<Self> {
91
96
  let parsed_deps = if let Some(list) = dependencies {
92
- parse_dependencies(py, list)?
97
+ Some(parse_dependencies(py, list)?)
93
98
  } else {
94
- Vec::new()
99
+ None
95
100
  };
96
101
  return Ok(Self {
97
102
  use_cache,
@@ -104,8 +109,15 @@ impl AutomagicDependencyCacheDecoratorFactory {
104
109
  fn __call__(&self, py: Python<'_>, func: Py<PyAny>) -> PyResult<DependencyCacheDecorator> {
105
110
  let method_name: String = func.getattr(py, "__name__")?.extract(py)?;
106
111
  let empty_args = PyTuple::empty(py);
107
- let hashed_dependencies: Vec<isize> = self
108
- .dependencies
112
+ let ast_dependencies;
113
+ let dependencies: &Vec<(String, Py<PyDict>)> = match &self.dependencies {
114
+ None => {
115
+ ast_dependencies = ast_inspect_method_dependencies(py, &func)?;
116
+ &ast_dependencies
117
+ }
118
+ Some(deps) => deps,
119
+ };
120
+ let hashed_dependencies: Vec<isize> = dependencies
109
121
  .iter()
110
122
  .map(|(method_name, kwargs)| {
111
123
  let (hash, _) = normalise_function_signature_and_hash(
@@ -113,7 +125,7 @@ impl AutomagicDependencyCacheDecoratorFactory {
113
125
  method_name,
114
126
  None,
115
127
  &empty_args,
116
- Some(&kwargs.bind(py)),
128
+ Some(kwargs.bind(py)),
117
129
  )?;
118
130
  Ok(hash)
119
131
  })
@@ -82,44 +82,6 @@ impl DependencyCacheBase {
82
82
  self.method_dependency_graph
83
83
  .add_children_dependency(hash, dependency, metadata);
84
84
  }
85
-
86
- // fn build_dependency_graph(cls: &Bound<'_, PyType>) -> PyResult<MethodDependencyGraph> {
87
- // let mut graph = MethodDependencyGraph::new();
88
- // let mut visited = HashSet::new();
89
- // let mut use_cache_methods = HashSet::new();
90
-
91
- // for mro_class in cls.mro().iter() {
92
- // let mro_class: Bound<'_, PyType> = mro_class.extract()?;
93
- // let namespace = mro_class.getattr("__dict__")?;
94
-
95
- // for item in namespace.call_method0("items")?.try_iter()? {
96
- // let (name, value): (String, Bound<'_, PyAny>) = item?.extract()?;
97
-
98
- // if name.starts_with("__") || !visited.insert(name.clone()) {
99
- // continue;
100
- // }
101
-
102
- // let Ok(decorator) = value.cast::<DependencyCacheDecorator>() else {
103
- // continue;
104
- // };
105
- // let decorator = decorator.borrow();
106
- // if !decorator.use_cache {
107
- // use_cache_methods.insert(name.clone());
108
- // };
109
- // graph.add_dependency(name, decorator.dependencies.clone());
110
- // }
111
- // }
112
- // let to_invalidate: Vec<String> = use_cache_methods
113
- // .iter()
114
- // .flat_map(|x| graph.methods_to_invalidate(x.to_string()))
115
- // .collect::<HashSet<String>>()
116
- // .into_iter()
117
- // .collect();
118
- // for method_name in to_invalidate {
119
- // graph.permanently_invalidate(method_name);
120
- // };
121
- // return Ok(graph);
122
- // }
123
85
  }
124
86
 
125
87
  #[pymethods]
@@ -134,18 +96,6 @@ impl DependencyCacheBase {
134
96
  };
135
97
  }
136
98
 
137
- // #[pyo3(signature = (*_args, **_kwargs))]
138
- // fn __init__(
139
- // slf: &Bound<'_, Self>,
140
- // _args: &Bound<'_, PyTuple>,
141
- // _kwargs: Option<&Bound<'_, PyDict>>,
142
- // ) -> PyResult<()> {
143
- // let cls = slf.get_type();
144
- // let graph = Self::build_dependency_graph(&cls)?;
145
- // slf.borrow_mut().method_dependency_graph = graph;
146
- // return Ok(());
147
- // }
148
-
149
99
  pub fn get_cached_value_by_hash(&self, py: Python<'_>, hash: isize) -> Option<Py<PyAny>> {
150
100
  if self.method_dependency_graph.is_valid(hash) {
151
101
  return self.cache.get(&hash).map(|obj| obj.clone_ref(py));
@@ -286,11 +236,7 @@ impl DependencyCacheBase {
286
236
  let mro_class: Bound<'_, PyType> = mro_class.extract()?;
287
237
  let namespace = mro_class.getattr("__dict__")?;
288
238
 
289
- // change methods to random order, since we do know what order is best
290
239
  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
240
  for method_name in method_names {
295
241
  let (name, value): (String, Bound<'_, PyAny>) = method_name?.extract()?;
296
242
  if name.starts_with("__") || !visited.insert(name.clone()) {
@@ -305,6 +251,8 @@ impl DependencyCacheBase {
305
251
  }
306
252
 
307
253
  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());
308
256
  for method_name in serialisable_methods {
309
257
  let value = slf.call_method(&method_name, (), None)?;
310
258
  result.set_item(method_name, value)?;
@@ -8,6 +8,7 @@ pub enum ValidationState {
8
8
  Invalid,
9
9
  PermanentlyInvalid,
10
10
  }
11
+
11
12
  pub struct MethodDependencyGraph<T, M = ()> {
12
13
  validation_state: HashMap<T, ValidationState>,
13
14
  dependency_graph: HashMap<T, HashSet<T>>, // maps child_name to set[parents_name], for ease of traversal
@@ -40,7 +41,7 @@ impl<T: Eq + Hash + Clone, M> MethodDependencyGraph<T, M> {
40
41
  }
41
42
 
42
43
  pub fn add_children_dependency(&mut self, method: T, dependencies: Vec<T>, metadata: M) -> () {
43
- if self.validation_state.contains_key(&method) {
44
+ if self.metadata_map.contains_key(&method) {
44
45
  return ();
45
46
  }
46
47
  self.validation_state.insert(method.clone(), ValidationState::Invalid);
@@ -1,3 +1,5 @@
1
+ use std::collections::HashSet;
2
+
1
3
  use pyo3::prelude::*;
2
4
  use pyo3::exceptions::PyValueError;
3
5
  use pyo3::types::{PyDict, PyString, PyTuple, PyList};
@@ -111,3 +113,92 @@ pub fn parse_dependencies(py: Python<'_>, dep_list: &Bound<'_, PyAny>) -> PyResu
111
113
 
112
114
  return Ok(parsed);
113
115
  }
116
+
117
+
118
+ fn visit(
119
+ py: Python<'_>,
120
+ node: &Bound<'_, PyAny>,
121
+ ast_module: &Bound<'_, PyModule>,
122
+ dependencies: &mut Vec<(String, Py<PyDict>)>,
123
+ visited: &mut HashSet<String>,
124
+ ) -> PyResult<()> {
125
+ let ast_call = ast_module.getattr("Call")?;
126
+ let ast_attribute = ast_module.getattr("Attribute")?;
127
+ let ast_name = ast_module.getattr("Name")?;
128
+
129
+ let attr = (|| -> PyResult<Option<String>> {
130
+ if !node.is_instance(&ast_call)? {
131
+ return Ok(None);
132
+ }
133
+ let args = node.getattr("args")?;
134
+ let keywords = node.getattr("keywords")?;
135
+ if args.len()? != 0 || keywords.len()? != 0 {
136
+ return Ok(None);
137
+ }
138
+ let func = node.getattr("func")?;
139
+ if !func.is_instance(&ast_attribute)? {
140
+ return Ok(None);
141
+ }
142
+ let value = func.getattr("value")?;
143
+ if !value.is_instance(&ast_name)? {
144
+ return Ok(None);
145
+ }
146
+ let id: String = value.getattr("id")?.extract()?;
147
+ if id != "self" {
148
+ return Ok(None);
149
+ }
150
+ Ok(Some(func.getattr("attr")?.extract()?))
151
+ })()?;
152
+
153
+ if let Some(attr) = attr {
154
+ if visited.insert(attr.clone()) {
155
+ let empty_dict = PyDict::new(py);
156
+ dependencies.push((attr, empty_dict.unbind()));
157
+ }
158
+ }
159
+
160
+
161
+ for child in ast_module
162
+ .call_method1("iter_child_nodes", (node,))?
163
+ .try_iter()?
164
+ {
165
+ visit(py, &child?, ast_module, dependencies, visited)?;
166
+ }
167
+
168
+ Ok(())
169
+ }
170
+
171
+
172
+ pub fn ast_inspect_method_dependencies(py: Python<'_>, python_func: &Py<PyAny>) -> PyResult<Vec<(String, Py<PyDict>)>> {
173
+ let inspect = PyModule::import(py, "inspect")?;
174
+ let function_string: String = inspect
175
+ .call_method1("getsource", (python_func.bind(py),))?
176
+ .extract()?;
177
+ let textwrap = PyModule::import(py, "textwrap")?;
178
+ let function_string_clean: String = textwrap
179
+ .call_method1("dedent", (function_string,))?
180
+ .call_method0("strip")?
181
+ .extract()?;
182
+ let ast_module = PyModule::import(py, "ast")?;
183
+ let ast_tree = ast_module
184
+ .call_method1("parse", (function_string_clean,))
185
+ .map_err(|e| PyValueError::new_err(format!("failed to parse source: {e}")))?;
186
+
187
+ let ast_function = ast_module.getattr("FunctionDef")?;
188
+ let ast_async_function = ast_module.getattr("AsyncFunctionDef")?;
189
+
190
+ let mut dependencies: Vec<(String, Py<PyDict>)> = Vec::new();
191
+ let mut visited: HashSet<String> = HashSet::new();
192
+
193
+ for node in ast_tree.getattr("body")?.try_iter()? {
194
+ let node = node?;
195
+ if !node.is_instance(&ast_function)? && !node.is_instance(&ast_async_function)? {
196
+ continue;
197
+ }
198
+ for statement in node.getattr("body")?.try_iter()? {
199
+ let statement = statement?;
200
+ visit(py, &statement, &ast_module, &mut dependencies, &mut visited)?
201
+ }
202
+ };
203
+ return Ok(dependencies);
204
+ }
@@ -329,7 +329,7 @@ wheels = [
329
329
 
330
330
  [[package]]
331
331
  name = "dependency-cache"
332
- version = "0.1.2"
332
+ version = "0.1.4"
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'" },