Skip to content

Commit deb62f0

Browse files
committed
added recursive collection of dependencies of sub-Nodes
1 parent 018ca59 commit deb62f0

1 file changed

Lines changed: 18 additions & 1 deletion

File tree

src/edgygraph/nodes.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,37 @@ class Node[T: StateProtocol = StateProtocol, S: SharedProtocol = SharedProtocol]
1717
The node must implement the `__call__` method to run the node.
1818
"""
1919

20-
dependencies: list[str] = []
20+
dependencies: set[str] = set()
2121
"""The pip dependencies of the node (python packages). On initialization of the node a check is performed if the dependencies are installed with importlib. If not an error is raised."""
2222

2323
@classmethod
2424
def check_dependencies(cls) -> None:
2525
"""
2626
Checks if the dependencies of the node are installed.
27+
28+
Raises:
29+
ImportError: If a dependency is not installed.
2730
"""
2831
for dependency in cls.dependencies:
2932
try:
3033
metadata.version(dependency)
3134
except metadata.PackageNotFoundError:
3235
raise ImportError(f"Dependency {dependency} not found but required by node {cls.__name__}. Please install it with pip install {dependency}")
3336

37+
def __init_subclass__(cls) -> None:
38+
"""
39+
Called when a subclass is created. This is used to collect the dependencies of the node from parent classes.
40+
41+
Works recursively because it is called on each inheritance level. Therefore the dependencies of all parent classes are collected and stored in the class variable `dependencies` of the child class.
42+
"""
43+
super().__init_subclass__()
44+
45+
cls.dependencies = cls.dependencies.copy() # To not modify the class variable of the parent
46+
47+
for base in cls.__bases__: # Called on each inheritance level, therefore its recursive
48+
if not issubclass(base, Node):
49+
continue
50+
cls.dependencies.update(base.dependencies)
3451

3552
def __init__(self) -> None:
3653
self.check_dependencies()

0 commit comments

Comments
 (0)