From d03ba4a0d91c6207a6cbcac44ae0de73402f8697 Mon Sep 17 00:00:00 2001 From: SinzoL Date: Fri, 13 Mar 2026 08:17:56 +0800 Subject: [PATCH] fix: fix build_python_functions_file generating malformed source When global_imports is empty, the function produced a leading blank line followed by an extra trailing newline per function. This resulted in source code that fails linting tools and confuses downstream parsing. Rewrite the assembly logic to: - Only emit the import block when there are actual imports - Sort imports for deterministic output - Use a single join with double newlines for clean separation - End with exactly one trailing newline (PEP 8) Fixes #7209 --- .../src/autogen_core/code_executor/_func_with_reqs.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/python/packages/autogen-core/src/autogen_core/code_executor/_func_with_reqs.py b/python/packages/autogen-core/src/autogen_core/code_executor/_func_with_reqs.py index b236ea543de3..fdf20699075a 100644 --- a/python/packages/autogen-core/src/autogen_core/code_executor/_func_with_reqs.py +++ b/python/packages/autogen-core/src/autogen_core/code_executor/_func_with_reqs.py @@ -236,12 +236,12 @@ def build_python_functions_file( if isinstance(func, (FunctionWithRequirements, FunctionWithRequirementsStr)): global_imports.update(func.global_imports) - content = "\n".join(map(_import_to_str, global_imports)) + "\n\n" + parts: list[str] = [] + if global_imports: + parts.append("\n".join(sorted(map(_import_to_str, global_imports)))) + parts.extend(_to_code(func) for func in funcs) - for func in funcs: - content += _to_code(func) + "\n\n" - - return content + return "\n\n".join(parts) + "\n" def to_stub(func: Union[Callable[..., Any], FunctionWithRequirementsStr]) -> str: