dependency-cache 0.1.3__tar.gz → 0.2.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 (28) hide show
  1. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/PKG-INFO +5 -4
  2. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/README.md +4 -3
  3. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/pyproject.toml +1 -1
  4. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/python/dependency_cache/dependency_cache.pyi +3 -3
  5. dependency_cache-0.2.0/python/examples/runtime_dependencies_example.py +45 -0
  6. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/src/decorator_factory.rs +20 -8
  7. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/src/dependency_cache_base.rs +94 -67
  8. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/src/dependency_graph.rs +10 -1
  9. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/src/py_introspection_utils.rs +91 -0
  10. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/uv.lock +1 -1
  11. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/.github/workflows/CI.yml +0 -0
  12. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/.github/workflows/Test.yml +0 -0
  13. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/.gitignore +0 -0
  14. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/Cargo.lock +0 -0
  15. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/Cargo.toml +0 -0
  16. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/LICENSE +0 -0
  17. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/python/dependency_cache/__init__.py +0 -0
  18. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/python/dependency_cache/plot_dependency_graph.py +0 -0
  19. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/python/examples/automagic_dependency_example.py +0 -0
  20. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/python/examples/example.py +0 -0
  21. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/python/examples/function_calls_example.py +0 -0
  22. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/python/examples/inheritance_example.py +0 -0
  23. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/python/examples/manual_dependency_example.py +0 -0
  24. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/python/examples/use_cache_example.py +0 -0
  25. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/python/test_python.py +0 -0
  26. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/python/test_python_automagic.py +0 -0
  27. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/src/decorator.rs +0 -0
  28. {dependency_cache-0.1.3 → dependency_cache-0.2.0}/src/lib.rs +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dependency_cache
3
- Version: 0.1.3
3
+ Version: 0.2.0
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -17,7 +17,7 @@ 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
23
  A library for managing the caching of an object's methods with cache invalidation handled by a dependency graph.
@@ -118,8 +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
- - add back in ast parsing, to decorator factory
122
- - 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
123
124
  - add object thread safety for python 3.14+
124
125
  - work out how best to handle nested objects
125
126
 
@@ -1,5 +1,5 @@
1
1
  # Dependency Cache
2
- ## :construction: Work In Progress :construction:
2
+ ## 🚧 Work In Progress 🚧
3
3
 
4
4
  ### Description
5
5
  A library for managing the caching of an object's methods with cache invalidation handled by a dependency graph.
@@ -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
104
- - 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
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.3"
14
+ version = "0.2.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,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())
@@ -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
  })
@@ -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
 
@@ -83,43 +83,12 @@ impl DependencyCacheBase {
83
83
  .add_children_dependency(hash, dependency, metadata);
84
84
  }
85
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
- // }
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
+ }
123
92
  }
124
93
 
125
94
  #[pymethods]
@@ -134,25 +103,6 @@ impl DependencyCacheBase {
134
103
  };
135
104
  }
136
105
 
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
- pub fn get_cached_value_by_hash(&self, py: Python<'_>, hash: isize) -> Option<Py<PyAny>> {
150
- if self.method_dependency_graph.is_valid(hash) {
151
- return self.cache.get(&hash).map(|obj| obj.clone_ref(py));
152
- }
153
- return None;
154
- }
155
-
156
106
  #[pyo3(signature = (method_name, **kwargs))]
157
107
  pub fn get_cached_value(&self, py: Python<'_>, method_name: String, kwargs: Option<Py<PyDict>>) -> Option<Py<PyAny>> {
158
108
  let empty_args = PyTuple::empty(py);
@@ -180,6 +130,7 @@ impl DependencyCacheBase {
180
130
  }
181
131
 
182
132
  pub fn clear_cache(&mut self) {
133
+ self.method_dependency_graph.invalidate_all();
183
134
  self.cache.clear();
184
135
  }
185
136
 
@@ -276,7 +227,8 @@ impl DependencyCacheBase {
276
227
  Ok(dict)
277
228
  }
278
229
 
279
- 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>> {
280
232
  let cls = slf.get_type();
281
233
 
282
234
  let mut visited = HashSet::new();
@@ -300,10 +252,24 @@ impl DependencyCacheBase {
300
252
  }
301
253
  }
302
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
+
303
271
  let result = PyDict::new(py);
304
- // change methods to random order, since we do know what order is best
305
- serialisable_methods.shuffle(&mut rng());
306
- for method_name in serialisable_methods {
272
+ for method_name in ordered_methods {
307
273
  let value = slf.call_method(&method_name, (), None)?;
308
274
  result.set_item(method_name, value)?;
309
275
  }
@@ -311,21 +277,82 @@ impl DependencyCacheBase {
311
277
  Ok(result)
312
278
  }
313
279
 
280
+ #[pyo3(signature = (data, order=None))]
314
281
  pub fn load_cache<'py>(
315
282
  slf: &Bound<'_, Self>,
316
283
  py: Python<'py>,
317
284
  data: Bound<'py, PyDict>,
285
+ order: Option<Vec<String>>,
318
286
  ) -> PyResult<()> {
319
- for (key, loaded_value) in data.iter() {
320
- 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
+ };
321
300
 
322
- let _ = slf.call_method(&method_name, (), None)?;
301
+ let method_attr = class.getattr(name)?;
323
302
 
324
- let empty_args = PyTuple::empty(py);
325
- let (hash, _) = normalise_function_signature_and_hash(py, &method_name, None, &empty_args, None)
326
- .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();
327
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)))?;
328
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)?;
329
356
  }
330
357
 
331
358
  Ok(())
@@ -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);
@@ -158,6 +159,14 @@ impl<T: Eq + Hash + Clone, M> MethodDependencyGraph<T, M> {
158
159
  where M: Clone {
159
160
  return self.metadata_map.clone();
160
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
+ }
161
170
  }
162
171
 
163
172
  #[cfg(test)]
@@ -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.3"
332
+ version = "0.2.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'" },