Skip to content

Commit

Permalink
Correctly set the namespace for NamedExpr targets
Browse files Browse the repository at this point in the history
NamedExpr targets should not be bound in a comprehension namespace, but rather it's parent scope.
  • Loading branch information
dflook committed Nov 11, 2024
1 parent 2714b91 commit de2b9b5
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/python_minifier/rename/mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,27 @@ def add_parent_to_comprehension(node, namespace):

add_parent(generator.target, namespace=node)
add_parent(generator.iter, namespace=iter_namespace)
iter_namespace = node

for if_ in generator.ifs:
add_parent(if_, namespace=node)

iter_namespace = node

def namedexpr_namespace(node):
"""
Get the namespace for a NamedExpr target
"""

if not isinstance(node, (ast.ListComp, ast.DictComp, ast.SetComp, ast.GeneratorExp)):
return node

return namedexpr_namespace(node.namespace)

def add_parent_to_namedexpr(node):
assert isinstance(node, ast.NamedExpr)

add_parent(node.target, namespace=namedexpr_namespace(node.namespace))
add_parent(node.value, namespace=node.namespace)

def add_parent(node, namespace=None):
"""
Expand Down Expand Up @@ -161,6 +178,11 @@ def add_parent(node, namespace=None):
elif isinstance(node.ctx, ast.Store) and isinstance(get_parent(node), ast.AugAssign):
namespace.nonlocal_names.add(node.id)

if isinstance(node, ast.NamedExpr):
# NamedExpr is 'special'
add_parent_to_namedexpr(node)
return

for child in ast.iter_child_nodes(node):
add_parent(child, namespace=namespace)

Expand Down

0 comments on commit de2b9b5

Please sign in to comment.