Skip to content

Commit 41a183d

Browse files
authored
Fix DeprecationWarnings under Python 3.12 (#259)
* - Prevent DeprecationWarnings from ``ast.Str`` and ``ast.Num`` on Python 3.12 * - exclude coverage in places that will never match
1 parent 34954e2 commit 41a183d

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

CHANGES.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ Features
1818
Fixes
1919
+++++
2020

21+
- Prevent DeprecationWarnings from ``ast.Str`` and ``ast.Num`` on Python 3.12
22+
2123
- Forbid using some attributes providing access to restricted Python internals.
2224

2325

src/RestrictedPython/transformer.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,14 @@
2525
from ._compat import IS_PY38_OR_GREATER
2626

2727

28+
# Avoid DeprecationWarnings under Python 3.12 and up
29+
if IS_PY38_OR_GREATER:
30+
astStr = ast.Constant
31+
astNum = ast.Constant
32+
else: # pragma: no cover
33+
astStr = ast.Str
34+
astNum = ast.Num
35+
2836
# For AugAssign the operator must be converted to a string.
2937
IOPERATOR_TO_STR = {
3038
ast.Add: '+=',
@@ -272,7 +280,7 @@ def gen_unpack_spec(self, tpl):
272280
"""
273281
spec = ast.Dict(keys=[], values=[])
274282

275-
spec.keys.append(ast.Str('childs'))
283+
spec.keys.append(astStr('childs'))
276284
spec.values.append(ast.Tuple([], ast.Load()))
277285

278286
# starred elements in a sequence do not contribute into the min_len.
@@ -292,12 +300,12 @@ def gen_unpack_spec(self, tpl):
292300

293301
elif isinstance(val, ast.Tuple):
294302
el = ast.Tuple([], ast.Load())
295-
el.elts.append(ast.Num(idx - offset))
303+
el.elts.append(astNum(idx - offset))
296304
el.elts.append(self.gen_unpack_spec(val))
297305
spec.values[0].elts.append(el)
298306

299-
spec.keys.append(ast.Str('min_len'))
300-
spec.values.append(ast.Num(min_len))
307+
spec.keys.append(astStr('min_len'))
308+
spec.values.append(astNum(min_len))
301309

302310
return spec
303311

@@ -903,7 +911,7 @@ def visit_Attribute(self, node):
903911
node = self.node_contents_visit(node)
904912
new_node = ast.Call(
905913
func=ast.Name('_getattr_', ast.Load()),
906-
args=[node.value, ast.Str(node.attr)],
914+
args=[node.value, astStr(node.attr)],
907915
keywords=[])
908916

909917
copy_locations(new_node, node)
@@ -1107,7 +1115,7 @@ def visit_AugAssign(self, node):
11071115
value=ast.Call(
11081116
func=ast.Name('_inplacevar_', ast.Load()),
11091117
args=[
1110-
ast.Str(IOPERATOR_TO_STR[type(node.op)]),
1118+
astStr(IOPERATOR_TO_STR[type(node.op)]),
11111119
ast.Name(node.target.id, ast.Load()),
11121120
node.value
11131121
],

0 commit comments

Comments
 (0)