Skip to content

Commit 37d8189

Browse files
committed
Add frozendict to ast constants
1 parent 43c3438 commit 37d8189

2 files changed

Lines changed: 26 additions & 2 deletions

File tree

Lib/test/test_ast/test_ast.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2683,6 +2683,11 @@ def test_validation(self):
26832683
self.assertEqual(str(cm.exception),
26842684
"got an invalid type in Constant: list")
26852685

2686+
with self.assertRaises(TypeError) as cm:
2687+
self.compile_constant(frozendict({1: [2, 3]}))
2688+
self.assertEqual(str(cm.exception),
2689+
"got an invalid type in Constant: list")
2690+
26862691
def test_singletons(self):
26872692
for const in (None, False, True, Ellipsis, b''):
26882693
with self.subTest(const=const):
@@ -2692,13 +2697,15 @@ def test_singletons(self):
26922697
def test_values(self):
26932698
nested_tuple = (1,)
26942699
nested_frozenset = frozenset({1})
2700+
nested_frozendict = frozendict({1: 1})
26952701
for level in range(3):
26962702
nested_tuple = (nested_tuple, 2)
26972703
nested_frozenset = frozenset({nested_frozenset, 2})
2704+
nested_frozendict = frozendict({nested_frozendict: 2})
26982705
values = (123, 123.0, 123j,
26992706
"unicode", b'bytes',
2700-
tuple("tuple"), frozenset("frozenset"),
2701-
nested_tuple, nested_frozenset)
2707+
tuple("tuple"), frozenset("frozenset"), frozendict({"a": 1}),
2708+
nested_tuple, nested_frozenset, nested_frozendict)
27022709
for value in values:
27032710
with self.subTest(value=value):
27042711
result = self.compile_constant(value)

Python/ast.c

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,23 @@ validate_constant(PyObject *value)
198198
return 1;
199199
}
200200

201+
if (PyFrozenDict_CheckExact(value)) {
202+
ENTER_RECURSIVE();
203+
204+
Py_ssize_t pos = 0;
205+
PyObject *key, *val;
206+
207+
while (PyDict_Next(value, &pos, &key, &val)) {
208+
if (!validate_constant(key) || !validate_constant(val)) {
209+
LEAVE_RECURSIVE();
210+
return 0;
211+
}
212+
}
213+
214+
LEAVE_RECURSIVE();
215+
return 1;
216+
}
217+
201218
if (!PyErr_Occurred()) {
202219
PyErr_Format(PyExc_TypeError,
203220
"got an invalid type in Constant: %s",

0 commit comments

Comments
 (0)