Skip to content

Commit

Permalink
fix: Ensure importability of modules not included in __init__.py files (
Browse files Browse the repository at this point in the history
#5965)

* fix: ensure that modules not included in __init__.py files are importable

* test: add test for module import in custom component
  • Loading branch information
ogabrielluiz authored Jan 28, 2025
1 parent ea2685f commit 0ef54c5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/backend/base/langflow/utils/validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,13 @@ def prepare_global_scope(module):
warnings.simplefilter("ignore", LangChainDeprecationWarning)
imported_module = importlib.import_module(node.module)
for alias in node.names:
exec_globals[alias.name] = getattr(imported_module, alias.name)
try:
# First try getting it as an attribute
exec_globals[alias.name] = getattr(imported_module, alias.name)
except AttributeError:
# If that fails, try importing the full module path
full_module_path = f"{node.module}.{alias.name}"
exec_globals[alias.name] = importlib.import_module(full_module_path)
except ModuleNotFoundError as e:
msg = f"Module {node.module} not found. Please install it and try again"
raise ModuleNotFoundError(msg) from e
Expand Down
20 changes: 20 additions & 0 deletions src/backend/tests/unit/test_validate_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,26 @@ def build(self):
assert result.value == "test"


def test_create_class_module_import():
code = """
from langflow.custom import CustomComponent
from PIL import ImageDraw
class ExternalClass:
def __init__(self, value):
self.value = value
class MyComponent(CustomComponent):
def build(self):
return ExternalClass("test")
"""
class_name = "MyComponent"
created_class = create_class(code, class_name)
instance = created_class()
result = instance.build()
assert result.value == "test"


def test_create_class_with_multiple_external_classes():
code = """
from langflow.custom import CustomComponent
Expand Down

0 comments on commit 0ef54c5

Please sign in to comment.