diff --git a/exasol_advanced_analytics_framework/udf_framework/dynamic_modules.py b/exasol_advanced_analytics_framework/udf_framework/dynamic_modules.py index 8086ea4d..899e00ad 100644 --- a/exasol_advanced_analytics_framework/udf_framework/dynamic_modules.py +++ b/exasol_advanced_analytics_framework/udf_framework/dynamic_modules.py @@ -4,6 +4,15 @@ from types import ModuleType +def _create_module(name: str) -> ModuleType: + spec = importlib.machinery.ModuleSpec(name, None) + return importlib.util.module_from_spec(spec) + + +def _register_module_for_import(name: str, mod: ModuleType): + sys.modules[name] = mod + + def create_module(name: str) -> ModuleType: """ Dynamically create a python module using the specified name and @@ -12,9 +21,10 @@ def create_module(name: str) -> ModuleType: Additionally add a function add_to_module() to the module enabling other code to add classes and functions to the module. """ - spec = importlib.machinery.ModuleSpec(name, None) - mod = importlib.util.module_from_spec(spec) - sys.modules[name] = mod + mod = sys.modules.get(name) + if mod is None: + mod = _create_module(name) + _register_module_for_import(name, mod) def add_to_module(object: Any): object.__module__ = name diff --git a/tests/unit_tests/udf_framework/test_dynamic_modules.py b/tests/unit_tests/udf_framework/test_dynamic_modules.py index ba1db1c0..b4f08a09 100644 --- a/tests/unit_tests/udf_framework/test_dynamic_modules.py +++ b/tests/unit_tests/udf_framework/test_dynamic_modules.py @@ -24,3 +24,17 @@ def test_add_function(): xx2.add_to_module(example_function) assert xx2.example_function() == "example_function return value" \ and example_function.__module__ == "xx2" + + +def test_add_function_to_existing_module(): + def my_func(): + return "another return value" + + mod1 = create_module("xx2") + import xx2 + xx2.add_to_module(example_function) + mod2 = create_module("xx2") + assert mod2 == mod1 + xx2.add_to_module(my_func) + assert xx2.example_function() == "example_function return value" \ + and xx2.my_func() == "another return value"