feat: Allow variables to be defined outside a Component (#4316)
* feat: Allow variables to be defined outside a Component Fixes #4315 Modify `prepare_global_scope` function in `src/backend/base/langflow/utils/validate.py` to evaluate classes, functions, and variables defined outside the Component's class. * **Function Changes:** - Add evaluation of external classes using `ast.ClassDef`. - Add evaluation of external functions using `ast.FunctionDef`. - Add evaluation of external variables using `ast.Assign`. * **Unit Tests:** - Add tests in `src/backend/tests/unit/test_validate_code.py` to verify the evaluation of external classes, functions, and variables. - Include tests for multiple external classes and external variables and functions. --- For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/langflow-ai/langflow/issues/4315?shareId=XXXX-XXXX-XXXX-XXXX). * [autofix.ci] apply automated fixes --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
This commit is contained in:
parent
fb0084d478
commit
ccba14bec4
4 changed files with 84 additions and 1 deletions
|
|
@ -227,6 +227,16 @@ def prepare_global_scope(code, module):
|
|||
except ModuleNotFoundError as e:
|
||||
msg = f"Module {node.module} not found. Please install it and try again"
|
||||
raise ModuleNotFoundError(msg) from e
|
||||
elif isinstance(node, ast.ClassDef):
|
||||
# Compile and execute the class definition to properly create the class
|
||||
class_code = compile(ast.Module(body=[node], type_ignores=[]), "<string>", "exec")
|
||||
exec(class_code, exec_globals)
|
||||
elif isinstance(node, ast.FunctionDef):
|
||||
function_code = compile(ast.Module(body=[node], type_ignores=[]), "<string>", "exec")
|
||||
exec(function_code, exec_globals)
|
||||
elif isinstance(node, ast.Assign):
|
||||
assign_code = compile(ast.Module(body=[node], type_ignores=[]), "<string>", "exec")
|
||||
exec(assign_code, exec_globals)
|
||||
return exec_globals
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue