Skip to content

Commit ca01803

Browse files
committed
handle assign within function
1 parent afb128f commit ca01803

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

IPython/core/guarded_eval.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -867,7 +867,8 @@ def dummy_function(*args, **kwargs):
867867

868868
def _infer_return_value(node: ast.FunctionDef, context: EvaluationContext):
869869
"""Infer the return value(s) of a function by evaluating all return statements."""
870-
return_values = _collect_return_values(node.body, context)
870+
func_context = context.replace(transient_locals=context.transient_locals.copy())
871+
return_values = _collect_return_values(node.body, func_context)
871872

872873
if not return_values:
873874
return None
@@ -896,9 +897,22 @@ def _infer_return_value(node: ast.FunctionDef, context: EvaluationContext):
896897

897898

898899
def _collect_return_values(body, context):
899-
"""Recursively collect return values from a list of AST statements."""
900+
"""Recursively collect return values from a list of AST statements.
901+
902+
For every assignment or annotated assignment, store them in context.transient_locals
903+
so that return statements can refer to them.
904+
"""
900905
return_values = []
901906
for stmt in body:
907+
# Handle assignments
908+
if isinstance(stmt, ast.Assign):
909+
_handle_assign(stmt, context)
910+
elif isinstance(stmt, ast.AnnAssign):
911+
if stmt.simple:
912+
context.transient_locals[stmt.target.id] = _resolve_annotation(
913+
eval_node(stmt.annotation, context), context
914+
)
915+
# Handle return statements
902916
if isinstance(stmt, ast.Return):
903917
if stmt.value is None:
904918
continue

tests/test_completer.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2178,6 +2178,17 @@ def _(expected):
21782178
),
21792179
"as_integer_ratio",
21802180
],
2181+
[
2182+
"\n".join(
2183+
[
2184+
"def foo():",
2185+
" l = []",
2186+
" return l",
2187+
"foo().",
2188+
]
2189+
),
2190+
"append",
2191+
],
21812192
],
21822193
)
21832194
def test_undefined_variables(use_jedi, evaluation, code, insert_text):

0 commit comments

Comments
 (0)