fix(python): explain Function namespace import restrictions (#4982)

A plain `import ctypes.util` in a Function currently reports “dynamic
namespace access” without explaining the module restriction or a way
forward. Give blocked module imports a distinct error that names the
modules, explains the reconstructed namespace constraint, and recommends
an importable helper supplied through `code=`, `pip=`, or `conda=`.
Dynamic namespace operations also get an actionable explanation.

Document the full restrictions and the helper alternative in the
decorator and Python Functions reference. Add regression coverage for
direct imports, `from` imports, global module aliases, class Functions,
the deprecated `@udf` alias, and helpers imported normally or shipped
with `code=`. Existing import restrictions remain in place.

For example, move `ctypes.util.find_library` into
`native_diagnostics/__init__.py`, then use:

```python
import native_diagnostics
from lancedb import function


@function(code=[native_diagnostics])
def probe_library(name: str) -> str:
    return native_diagnostics.find_library(name)
```

Fixes ENT-3408.
This commit is contained in:
Jack Ye
2026-11-12 09:01:39 -08:00
committed by GitHub
parent b4d1c55f62
commit e61e21035c
4 changed files with 214 additions and 21 deletions
@@ -888,7 +888,7 @@ def test_function_rejects_a_module_level_namespace_alias(tmp_path):
spec = importlib.util.spec_from_file_location("aliasing_udfs", module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
with pytest.raises(ValueError, match="dynamic namespace access"):
with pytest.raises(ValueError, match="imports from namespace-access modules"):
function(module.score)
@@ -899,7 +899,6 @@ def test_function_rejects_a_module_level_namespace_alias(tmp_path):
"eval('THRESHOLD')",
"(lambda g: g()['THRESHOLD'])(globals)",
"__import__('sys').modules[__name__].THRESHOLD",
"sys.modules[__name__].THRESHOLD",
],
)
def test_function_rejects_dynamic_namespace_access(access):
@@ -911,9 +910,7 @@ def test_function_rejects_dynamic_namespace_access(access):
)
with pytest.raises(ValueError, match="dynamic namespace access"):
_package_from_text(
"def score(value: int) -> int:\n"
" import sys\n"
f" return value + {access}\n"
f"def score(value: int) -> int:\n return value + {access}\n"
)