[New-bugs-announce] [issue42889] Incorrect behavior of Python parser after ast node of test program being modified

Xinmeng Xia report at bugs.python.org
Mon Jan 11 02:45:39 EST 2021

New submission from Xinmeng Xia <xiaxm at smail.nju.edu.cn>:

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:","------------")

c = compile(newast,'','exec')

output result:
new code: ------------
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 <report at bugs.python.org>

More information about the New-bugs-announce mailing list