Skip to content

Commit

Permalink
Fixed review findings
Browse files Browse the repository at this point in the history
  • Loading branch information
ckunki committed Oct 24, 2024
1 parent 2cdeb0d commit 7045dff
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
14 changes: 14 additions & 0 deletions tests/unit_tests/udf_framework/test_dynamic_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

0 comments on commit 7045dff

Please sign in to comment.