Skip to content

Commit d0f6727

Browse files
author
Evan Jones
committed
Should resolve #172, where OpenSCAD code was re-imported at every call to import_scad(). Now we cache it instead. This matches native Python import semantics better
1 parent f460842 commit d0f6727

File tree

2 files changed

+24
-6
lines changed

2 files changed

+24
-6
lines changed

solid/objects.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
ScadSize = Union[int, Sequence[float]]
2323
OpenSCADObjectPlus = Union[OpenSCADObject, Sequence[OpenSCADObject]]
2424

25+
IMPORTED_SCAD_MODULES: Dict[Path, SimpleNamespace] = {}
26+
2527
class polygon(OpenSCADObject):
2628
"""
2729
Create a polygon with the specified points and paths.
@@ -761,15 +763,23 @@ def import_scad(scad_file_or_dir: PathStr) -> SimpleNamespace:
761763
OpenSCAD files. Create Python mappings for all OpenSCAD modules & functions
762764
Return a namespace or raise ValueError if no scad files found
763765
'''
766+
global IMPORTED_SCAD_MODULES
767+
764768
scad = Path(scad_file_or_dir)
765769
candidates: List[Path] = [scad]
766-
if not scad.is_absolute():
767-
candidates = [d/scad for d in _openscad_library_paths()]
768770

769-
for candidate_path in candidates:
770-
namespace = _import_scad(candidate_path)
771-
if namespace is not None:
772-
return namespace
771+
ns = IMPORTED_SCAD_MODULES.get(scad)
772+
if ns:
773+
return ns
774+
else:
775+
if not scad.is_absolute():
776+
candidates = [d/scad for d in _openscad_library_paths()]
777+
778+
for candidate_path in candidates:
779+
namespace = _import_scad(candidate_path)
780+
if namespace is not None:
781+
IMPORTED_SCAD_MODULES[scad] = namespace
782+
return namespace
773783
raise ValueError(f'Could not find .scad files at or under {scad}. \nLocations searched were: {candidates}')
774784

775785
def _import_scad(scad: Path) -> Optional[SimpleNamespace]:

solid/test/test_solidpython.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,14 @@ def test_import_scad(self):
227227
# are imported correctly. Not sure how to do this without writing
228228
# temp files to those directories. Seems like overkill for the moment
229229

230+
def test_multiple_import_scad(self):
231+
# For Issue #172. Originally, multiple `import_scad()` calls would
232+
# re-import the entire module, rather than cache a module after one use
233+
include_file = self.expand_scad_path("examples/scad_to_include.scad")
234+
mod1 = import_scad(include_file)
235+
mod2 = import_scad(include_file)
236+
self.assertEqual(mod1, mod2)
237+
230238
def test_imported_scad_arguments(self):
231239
include_file = self.expand_scad_path("examples/scad_to_include.scad")
232240
mod = import_scad(include_file)

0 commit comments

Comments
 (0)