8000 bpo-40870: Invalidate usage of some constants with ast.Name (GH-20649) · python/cpython@68874a8 · GitHub
[go: up one dir, main page]

Skip to content

Commit 68874a8

Browse files
authored
bpo-40870: Invalidate usage of some constants with ast.Name (GH-20649)
1 parent 5552850 commit 68874a8

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

Lib/test/test_ast.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -668,6 +668,13 @@ def test_issue40614_feature_version(self):
668668
with self.assertRaises(SyntaxError):
669669
ast.parse('f"{x=}"', feature_version=(3, 7))
670670

671+
def test_constant_as_name(self):
672+
for constant in "True", "False", "None":
673+
expr = ast.Expression(ast.Name(constant, ast.Load()))
674+
ast.fix_missing_locations(expr)
675+
with self.assertRaisesRegex(ValueError, f"Name node can't be used with '{constant}' constant"):
676+
compile(expr, "<test>", "eval")
677+
671678

672679
class ASTHelpers_Test(unittest.TestCase):
673680
maxDiff = None
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Raise :exc:`ValueError` when validating custom AST's where the constants
2+
``True``, ``False`` and ``None`` are used within a :class:`ast.Name` node.

Python/ast.c

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,25 @@ static int validate_nonempty_seq(asdl_seq *, const char *, const char *);
2121
static int validate_stmt(stmt_ty);
2222
static int validate_expr(expr_ty, expr_context_ty);
2323

24+
static int
25+
validate_name(PyObject *name)
26+
{
27+
assert(PyUnicode_Check(name));
28+
static const char * const forbidden[] = {
29+
"None",
30+
"True",
31+
"False",
32+
NULL
33+
};
34+
for (int i = 0; forbidden[i] != NULL; i++) {
35+
if (_PyUnicode_EqualToASCIIString(name, forbidden[i])) {
36+
PyErr_Format(PyExc_ValueError, "Name node can't be used with '%s' constant", forbidden[i]);
37+
return 0;
38+
}
39+
}
40+
return 1;
41+
}
42+
2443
static int
2544
validate_comprehension(asdl_seq *gens)
2645
{
@@ -173,6 +192,9 @@ validate_expr(expr_ty exp, expr_context_ty ctx)
173192
actual_ctx = exp->v.Starred.ctx;
174193
break;
175194
case Name_kind:
195+
if (!validate_name(exp->v.Name.id)) {
196+
return 0;
197+
}
176198
actual_ctx = exp->v.Name.ctx;
177199
break;
178200
case List_kind:

0 commit comments

Comments
 (0)
0