New submission from Xinmeng Xia <[email protected]>:
The following program will lead to a incorrect behavior of Python parser. We
change all variable to integer( forcely transformed to string) via
ast.NodeTransformer. Then we compile the new code and execute it. It's
surprising that code like "1=2; print(1)" can be compiled without error
message. And more surprisingly, the execution result of "print(1)" is 2 ! !
====================================
import ast
class RewriteName(ast.NodeTransformer):
def visit_Name(self, node):
if node.id != "print":
node.id = str(node.lineno)
return node
code = "a = 2;print(a)"
myast = ast.parse(code)
transformer = RewriteName()
newast = transformer.visit(myast)
# print(ast.dump(newast))
print("new code:","------------")
print(ast.unparse(newast))
print("------------")
c = compile(newast,'','exec')
exec(c)
=================================
output result:
new code: ------------
1 = 2
print(1)
------------
2
Expected result: (1). Syntax error during compilation. "1" should not be the
correct identifier of program, even if it's forcely transformed to string. (2).
The output of execution should be "1" , since the parameter of "print()" in
the new code is string "1".
This incorrect behaviors exists on all version of Python(from Python2 to Python
3).
----------
components: Interpreter Core
messages: 384799
nosy: xxm
priority: normal
severity: normal
status: open
title: Incorrect behavior of Python parser after ast node of test program
being modified
type: behavior
versions: Python 3.10, Python 3.6, Python 3.7, Python 3.8, Python 3.9
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue42889>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com