Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Lib/test/test_compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ def test_other_newlines(self):
compile("hi\r\nstuff\r\ndef f():\n pass\r", "<test>", "exec")
compile("this_is\rreally_old_mac\rdef f():\n pass", "<test>", "exec")

def test_assignment_to_name_surrounded_by_parentheses(self):
self.assertRaises(SyntaxError, compile, '(x) = 1', '?', 'single')
self.assertRaises(SyntaxError, compile, 'x=1; (x) += 1', '?', 'single')

def test_debug_assignment(self):
# catch assignments to __debug__
self.assertRaises(SyntaxError, compile, '__debug__ = 1', '?', 'single')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Assignments to single names surrounded by parenthesis (i.e. :code:`(x) =
42`) now raises :exc:`SyntaxError`.
28 changes: 28 additions & 0 deletions Python/ast.c
Original file line number Diff line number Diff line change
Expand Up @@ -2882,6 +2882,23 @@ ast_for_testlist(struct compiling *c, const node* n)
}
}

static bool
name_is_surrounded_by_parens(node *n)
{
node *current = n;

while (current != NULL && TYPE(current) != atom) {
current = CHILD(current, 0);
}

if (current == NULL || NCH(current) != 3) {
return 0;
}

return (TYPE(CHILD(current, 0)) == LPAR
&& TYPE(CHILD(current, 2)) == RPAR);
}

static stmt_ty
ast_for_expr_stmt(struct compiling *c, const node *n)
{
Expand Down Expand Up @@ -2918,6 +2935,11 @@ ast_for_expr_stmt(struct compiling *c, const node *n)
those. */
switch (expr1->kind) {
case Name_kind:
if (name_is_surrounded_by_parens(ch)) {
ast_error(c, ch, "a single name cannot be surrounded by "
"parentheses in an assignment");
return NULL;
}
case Attribute_kind:
case Subscript_kind:
break;
Expand Down Expand Up @@ -3032,6 +3054,12 @@ ast_for_expr_stmt(struct compiling *c, const node *n)
if (!e)
return NULL;

if (e->kind == Name_kind && name_is_surrounded_by_parens(ch)) {
ast_error(c, ch, "a single name cannot be surrounded by "
"parentheses in an assignment");
return NULL;
}

/* set context to assign */
if (!set_context(c, e, Store, CHILD(n, i)))
return NULL;
Expand Down