Terry J. Reedy <tjre...@udel.edu> added the comment:

The parser is not involved here.  The transformed code is *not* equivalent to 
"1=2; print(1)" because you replace 'a' with the string '1', not the int 1.  
The result is to transform
 "globals()['a']=2; print(globals()['a'])" to 
 "globals()['1']=2; print(globals()['1'])"
This works because globals() is a regular dict.

If one does try to make the code equivalent to "1=2; print(1)" by replacing 
with 1, the result is an error.

Traceback (most recent call last):
  File "F:\Python\a\tem4.py", line 19, in <module>
    print(ast.unparse(newast))
  File "C:\Programs\Python310\lib\ast.py", line 1567, in unparse
    return unparser.visit(ast_obj)
  File "C:\Programs\Python310\lib\ast.py", line 805, in visit
    return "".join(self._source)
TypeError: sequence item 1: expected str instance, int found

With unparse removed, I get a compile error when the identifier type is checked.

Traceback (most recent call last):
  File "F:\Python\a\tem4.py", line 19, in <module>
    c = compile(newast,'','exec')
TypeError: AST identifier must be of type str

In the binary example, unparsing gives an infinite recursion error with this 
repeated sequence.

  File "C:\Programs\Python310\lib\ast.py", line 1372, in visit_BinOp
    self.traverse(node.left)
  File "C:\Programs\Python310\lib\ast.py", line 798, in traverse
    super().visit(node)
  File "C:\Programs\Python310\lib\ast.py", line 410, in visit
    return visitor(node)

Without unparse, the compile call crashes.  (In IDLE, this means there is an 
unrequested restart of the Shell subprocess that executes user code, without 
IDLE crashing.)  I suspect that there is a related loop in the compile C code 
that crashes the process before any checking is done.  If so, the situation 
would be similar to your #42887 and we may not be able to do anything.

----------
nosy: +terry.reedy
title: Incorrect behavior of Python parser after ast node of test program  
being modified -> Incorrect behavior  after ast node visits
versions:  -Python 3.6, Python 3.7

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue42889>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to