Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/lfx/src/lfx/custom/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,8 @@ def _resolve_attribute(imported_module, module_name, attr_name):
def _handle_module_attributes(imported_module, node, module_name, exec_globals):
"""Handle importing specific attributes from a module."""
for alias in node.names:
exec_globals[alias.name] = _resolve_attribute(imported_module, module_name, alias.name)
key = alias.asname or alias.name
exec_globals[key] = _resolve_attribute(imported_module, module_name, alias.name)


class _MissingModulePlaceholder:
Expand Down
32 changes: 32 additions & 0 deletions src/lfx/tests/unit/custom/component/test_validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,38 @@ def to_url(path):
assert scope["urllib"].request.pathname2url("folder name/file.txt") == "folder%20name/file.txt"


def test_prepare_global_scope_supports_aliased_from_imports():
"""Regression test: `from X import Y as Z` must bind Z in scope, not Y."""
module = ast.parse(
dedent("""
from urllib.request import pathname2url as to_url_path

def to_url(path):
return to_url_path(path)
""")
)
scope = prepare_global_scope(module)

assert "to_url_path" in scope
assert "pathname2url" not in scope
assert scope["to_url_path"]("folder name/file.txt") == "folder%20name/file.txt"


def test_create_class_supports_aliased_from_imports():
"""End-to-end: a component using `from X import Y as Z` should load and Z is usable."""
code = dedent("""
from urllib.request import pathname2url as to_url_path
from lfx.custom import Component

class AliasedImportComponent(Component):
def to_url(self, path):
return to_url_path(path)
""")
cls = create_class(code, "AliasedImportComponent")
assert cls.__name__ == "AliasedImportComponent"
assert cls().to_url("folder name/file.txt") == "folder%20name/file.txt"


# ---------------------------------------------------------------------------
# _get_module_fallbacks
# ---------------------------------------------------------------------------
Expand Down
Loading