Skip to content

Commit 0b81d8c

Browse files
committed
fix(frontend): don't count a lambda's default parameters as loop variables
A lambda's parameter list is not bracketed, so the `=` of a default parameter was taken for an assignment: `pick = lambda row, col='line': row[col]` gave the loop variables pick and col, and the panel offered a `$col` no Loop Start sets. After the statement's first top-level `lambda`, an `=` is no longer read as an assignment.
1 parent 1cc8bae commit 0b81d8c

2 files changed

Lines changed: 18 additions & 0 deletions

File tree

‎frontend/src/app/workspace/util/loop-variable.util.spec.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,15 @@ describe("extractLoopVariables", () => {
8686
expect(extractLoopVariables("g = lambda k=1: k")).toEqual(["g"]);
8787
});
8888

89+
it("excludes a lambda's default parameters wherever they sit in its parameter list", () => {
90+
expect(extractLoopVariables("pick = lambda row, col='line': row[col]")).toEqual(["pick"]);
91+
expect(extractLoopVariables("i = 0\nkey = lambda s, n=1: s[:n]")).toEqual(["i", "key"]);
92+
expect(extractLoopVariables("f = lambda x=1: x")).toEqual(["f"]);
93+
expect(extractLoopVariables("g = lambda: 0")).toEqual(["g"]);
94+
expect(extractLoopVariables("longest = max(names, key=lambda s, n=1: len(s))")).toEqual(["longest"]);
95+
expect(extractLoopVariables("a = b = lambda x, y=2: x")).toEqual(["a", "b"]);
96+
});
97+
8998
// Python has no block scope: the exec'd initialization binds, as globals of the state, whatever an
9099
// if/else, try/except, for or while body assigns, so those are loop variables too.
91100
it("reads assignments under a top-level if/else, try/except and while", () => {

‎frontend/src/app/workspace/util/loop-variable.util.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,9 +287,18 @@ function importItemName(item: string, isModule: boolean): string[] {
287287

288288
/** The names a plain statement assigns, e.g. `a = b = 0` -> a, b; `x += 1` or `f(k=1)` -> nothing. */
289289
function assignedNames(statement: string): string[] {
290+
// A lambda's parameters are not bracketed, so the `=` of a default (`lambda s, n=1: ...`) is top-level;
291+
// after the first top-level `lambda`, an `=` is never an assignment.
292+
const lambda = topLevelPositions(
293+
statement,
294+
(text, i) => /^lambda\b/.test(text.slice(i)) && /[^A-Za-z0-9_.]/.test(text[i - 1] ?? " ")
295+
)[0];
290296
const names: string[] = [];
291297
let from = 0;
292298
for (const position of assignmentPositions(statement)) {
299+
if (lambda !== undefined && position > lambda) {
300+
break;
301+
}
293302
names.push(...targetNames(statement.slice(from, position)));
294303
from = position + 1;
295304
}

0 commit comments

Comments
 (0)