fix(python): allow static diagnostic imports in Functions (#5084)

Functions previously rejected every `sys` or `importlib` import even
when the source only used a statically visible diagnostic. Allow exactly
`sys.stderr`, `sys.version_info`, and `importlib.metadata.version`, with
direct imports, `from` imports, and aliases treated identically whether
they appear at module level or inside the function or class body.

Every other use of a namespace-access module still fails at decoration.
The error now names the rejected operation, such as `sys.modules`, and
lists the supported diagnostic operations.

Tests package and execute the artifact offline for each import form, and
reject unsupported attributes, submodules, dynamic attribute access, and
rebinding. ENT-3918.
This commit is contained in:
Xuanwo
2026-11-18 16:15:42 +08:00
committed by GitHub
parent 4cab7d0b6f
commit a653d861ec
4 changed files with 407 additions and 47 deletions
+19
View File
@@ -767,6 +767,25 @@ seen and unsupported where it cannot: `globals()`, `eval`, `sys.modules`,
`builtins`. Closures and a non-standard `__builtins__` are rejected outright.
</Warning>
Three statically recognizable diagnostic operations are supported: `sys.stderr`,
`sys.version_info`, and `importlib.metadata.version`. Direct imports, `from`
imports, and aliases work the same way. Any other use of `sys`, `builtins`,
`importlib`, `inspect`, `gc`, `ctypes`, or `types` is rejected; move it into an
importable helper module.
```python
import importlib.metadata
import sys
from lancedb import function
@function(pip=["numpy"])
def report(value: int) -> str:
print("diagnostic", file=sys.stderr)
return f"numpy {importlib.metadata.version('numpy')} on {sys.version_info}"
```
In practice this means a function should be self-contained: take its inputs as
arguments, import what it needs at module level, and avoid capturing state from
the surrounding scope.