fix: Ensure importability of modules not included in __init__.py files (#5965)
* fix: ensure that modules not included in __init__.py files are importable * test: add test for module import in custom component
This commit is contained in:
parent
ea2685fb83
commit
0ef54c5ad9
2 changed files with 27 additions and 1 deletions
|
|
@ -244,7 +244,13 @@ def prepare_global_scope(module):
|
||||||
warnings.simplefilter("ignore", LangChainDeprecationWarning)
|
warnings.simplefilter("ignore", LangChainDeprecationWarning)
|
||||||
imported_module = importlib.import_module(node.module)
|
imported_module = importlib.import_module(node.module)
|
||||||
for alias in node.names:
|
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:
|
except ModuleNotFoundError as e:
|
||||||
msg = f"Module {node.module} not found. Please install it and try again"
|
msg = f"Module {node.module} not found. Please install it and try again"
|
||||||
raise ModuleNotFoundError(msg) from e
|
raise ModuleNotFoundError(msg) from e
|
||||||
|
|
|
||||||
|
|
@ -127,6 +127,26 @@ class MyComponent(CustomComponent):
|
||||||
assert result.value == "test"
|
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():
|
def test_create_class_with_multiple_external_classes():
|
||||||
code = """
|
code = """
|
||||||
from langflow.custom import CustomComponent
|
from langflow.custom import CustomComponent
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue