Skip to content

Commit aa13adf

Browse files
authored
Work around mypyc not supporting default arguments in closure (#6671)
mypyc doesn't yet properly implement the "bind on function definition" behavior of default arguments, which means that can't be abused to capture variables in nested function defined in a loop. Work around this in a hacky way.
1 parent d920bd7 commit aa13adf

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

mypy/server/aststripnew.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,7 @@ def prepare_implicit_var_patches(self, node: ClassDef) -> None:
8787
if isinstance(sym.node, Var) and sym.implicit:
8888
explicit_self_type = sym.node.explicit_self_type
8989

90-
# These arguments should not be passed, we just want to capture
91-
# the names in closure at current iteration in the for-loop.
92-
def patch(name: str = name, sym: SymbolTableNode = sym) -> None:
90+
def patch(name: str, sym: SymbolTableNode) -> None:
9391
existing = node.info.get(name)
9492
defined_in_this_class = name in node.info.names
9593
# This needs to mimic the logic in SemanticAnalyzer.analyze_member_lvalue()
@@ -103,7 +101,10 @@ def patch(name: str = name, sym: SymbolTableNode = sym) -> None:
103101
explicit_self_type and not defined_in_this_class):
104102
node.info.names[name] = sym
105103

106-
self.patches.append(patch)
104+
# Capture the current name, sym in a weird hacky way,
105+
# because mypyc doesn't yet support capturing them in
106+
# the usual hacky way (as default arguments).
107+
self.patches.append((lambda name, sym: lambda: patch(name, sym))(name, sym))
107108

108109
def visit_func_def(self, node: FuncDef) -> None:
109110
if not self.recurse_into_functions:

0 commit comments

Comments
 (0)