Skip to content

Commit

Permalink
Allow semantic paths
Browse files Browse the repository at this point in the history
  • Loading branch information
liamhuber committed Jan 4, 2024
1 parent 2000a8d commit 56ec6a3
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
27 changes: 25 additions & 2 deletions pyiron_workflow/interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class Creator(metaclass=Singleton):
"""

def __init__(self):
self._package_access = {}
self._package_access = DotDict()
self._package_registry = bidict()

self.Executor = Executor
Expand Down Expand Up @@ -178,7 +178,10 @@ def register(self, domain: str, package_identifier: str) -> None:

try:
module = import_module(package_identifier)
container = self._package_access # TODO: walk the dots in domain
if "." in domain:
domain, container = self._get_deep_container(domain)
else:
container = self._package_access
self._register_recursively_from_module(module, domain, container)
except ModuleNotFoundError as e:
raise ModuleNotFoundError(
Expand All @@ -187,6 +190,26 @@ def register(self, domain: str, package_identifier: str) -> None:
f"looks like a module, perhaps it's simply not in your path?"
) from e

def _get_deep_container(self, semantic_domain: str) -> tuple[str, DotDict]:
from pyiron_workflow.node_package import NodePackage

container = self._package_access
path = semantic_domain.split(".")

while len(path) > 1:
step = path.pop(0)
if not hasattr(container, step):
container[step] = DotDict()
elif isinstance(container[step], NodePackage):
raise ValueError(
f"The semantic path {semantic_domain} is invalid because it uses "
f"{step} as an intermediary, but this is already a "
f"{NodePackage.__name__}"
)
container = container[step]
domain = path[0]
return domain, container

def _register_recursively_from_module(
self, module: ModuleType, domain: str, container: DotDict
) -> None:
Expand Down
13 changes: 13 additions & 0 deletions tests/unit/test_interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,19 @@ def test_registration(self):
some_field = self.creator.dir()[0]
self.creator.register(some_field, "static.demo_nodes")

with self.subTest("Test semantic domain"):
self.creator.register("some.path", "static.demo_nodes")
self.assertIsInstance(self.creator.some.path, NodePackage)

self.creator.register("some.deeper.path", "static.demo_nodes")
self.assertIsInstance(self.creator.some.deeper.path, NodePackage)

with self.assertRaises(
ValueError,
msg="Can't inject a branch on a package"
):
self.creator.register("some.path.deeper", "static.demo_nodes")

with self.subTest("Test failure cases"):
n_initial_packages = len(self.creator._package_access)

Expand Down

0 comments on commit 56ec6a3

Please sign in to comment.