Skip to content

Commit bbfcd0f

Browse files
committed
module_name parameter for compile_python
1 parent b2206a4 commit bbfcd0f

File tree

2 files changed

+46
-5
lines changed

2 files changed

+46
-5
lines changed

linkml_runtime/utils/compile_python.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,21 @@ def file_text(txt_or_fname: str) -> str:
1616
return txt_or_fname
1717

1818

19-
def compile_python(text_or_fn: str, package_path: str = None) -> ModuleType:
19+
def compile_python(text_or_fn: str, package_path: str | None = None, module_name: str | None = None) -> ModuleType:
2020
"""
2121
Compile the text or file and return the resulting module
2222
@param text_or_fn: Python text or file name that references python file
23-
@param package_path: Root package path. If omitted and we've got a python file, the package is the containing
24-
directory
23+
@param package_path: Root package path. If omitted and we've got a python file, the package is the containing directory
24+
@param module_name: to be used in an import statement, default 'test'
2525
@return: Compiled module
2626
"""
27+
if module_name is None:
28+
module_name = "test"
2729
python_txt = file_text(text_or_fn)
2830
if package_path is None and python_txt != text_or_fn:
2931
package_path = text_or_fn
30-
spec = compile(python_txt, 'test', 'exec')
31-
module = ModuleType('test')
32+
spec = compile(python_txt, module_name, 'exec')
33+
module = ModuleType(module_name)
3234
if package_path:
3335
package_path_abs = os.path.join(os.getcwd(), package_path)
3436
# We have to calculate the path to expected path relative to the current working directory
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import pytest
2+
from linkml_runtime.utils.compile_python import compile_python
3+
4+
5+
@pytest.fixture
6+
def module_1():
7+
return """
8+
x: int = 2
9+
10+
def fun(value: int):
11+
return f'known value {value}'
12+
"""
13+
14+
15+
@pytest.fixture
16+
def module_2():
17+
return """
18+
import module_1 as m
19+
20+
def more_fun(message: str):
21+
return f'got "{message}"'
22+
"""
23+
24+
25+
def test_compile(module_1, module_2):
26+
m1 = compile_python(module_1, module_name="module_1")
27+
assert m1.__name__ == "module_1"
28+
assert m1.x == 2
29+
assert m1.fun(3) == "known value 3"
30+
m2 = compile_python(module_2, module_name="module_2", package_path=".")
31+
assert m2.__name__ == "module_2"
32+
assert m2.more_fun("hello") == 'got "hello"'
33+
assert m2.m.fun(4) == "known value 4"
34+
assert m2.m.x == 2
35+
36+
37+
def test_default_module_name(module_1):
38+
m = compile_python(module_1)
39+
assert m.__name__ == "test"

0 commit comments

Comments
 (0)