Skip to content

Commit bfcf119

Browse files
committed
Fix deprecation warning when creating AST node without required fields
Python 3.13 added the warning which will become an error in Python 3.15 (see python/cpython#105880)
1 parent c4afb78 commit bfcf119

File tree

3 files changed

+23
-7
lines changed

3 files changed

+23
-7
lines changed

genshi/template/astutil.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -802,7 +802,7 @@ def visit(self, node):
802802
return visitor(node)
803803

804804
def _clone(self, node):
805-
clone = node.__class__()
805+
clone = construct_ast_class(node.__class__)
806806
for name in getattr(clone, '_attributes', ()):
807807
try:
808808
setattr(clone, name, getattr(node, name))
@@ -887,3 +887,17 @@ def _clone(self, node):
887887
visit_Index = _clone
888888

889889
del _clone
890+
891+
892+
def construct_ast_class(cls):
893+
kwargs = {}
894+
for name, typ in cls.__annotations__.items():
895+
if typ is str:
896+
kwargs[name] = 'foo'
897+
elif typ is int:
898+
kwargs[name] = 42
899+
elif typ is object:
900+
kwargs[name] = b'foo'
901+
elif isinstance(typ, type) and issubclass(typ, _ast.AST):
902+
kwargs[name] = construct_ast_class(typ)
903+
return cls(**kwargs)

genshi/template/eval.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@
2020
from six.moves import builtins
2121

2222
from genshi.core import Markup
23-
from genshi.template.astutil import ASTTransformer, ASTCodeGenerator, parse
23+
from genshi.template.astutil import (
24+
ASTTransformer, ASTCodeGenerator, parse, construct_ast_class)
2425
from genshi.template.base import TemplateRuntimeError
2526
from genshi.util import flatten
2627

@@ -61,11 +62,9 @@ def __init__(self, source, filename=None, lineno=-1, lookup='strict',
6162
'Expected string or AST node, but got %r' % source
6263
self.source = '?'
6364
if self.mode == 'eval':
64-
node = _ast.Expression()
65-
node.body = source
65+
node = _ast.Expression(body=source)
6666
else:
67-
node = _ast.Module()
68-
node.body = [source]
67+
node = _ast.Module(body=[source])
6968

7069
self.ast = node
7170
self.code = _compile(node, self.source, mode=self.mode,
@@ -456,7 +455,7 @@ def _compile(node, source=None, mode='eval', filename=None, lineno=-1,
456455

457456

458457
def _new(class_, *args, **kwargs):
459-
ret = class_()
458+
ret = construct_ast_class(class_)
460459
for attr, value in zip(ret._fields, args):
461460
if attr in kwargs:
462461
raise ValueError('Field set both in args and kwargs')

pytest.ini

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
11
[pytest]
22
addopts = --doctest-modules
33
doctest_optionflags = NORMALIZE_WHITESPACE ALLOW_UNICODE
4+
filterwarnings =
5+
error
6+
ignore:pkg_resources

0 commit comments

Comments
 (0)