Python ast (gast) module - multiple copies of same object

Viewed 87

I passed the following code through gast.parse and tried to see different name objects

def foo(n:int)->int:
  if n > 0:
    return 1
  elif n < 0:
    return -1
  else:
    return 0

Here is what I got as the output

function arg: <gast.gast.Name object at 0x7f84c085b3c8> , name= n
compare sees: <gast.gast.Name object at 0x7f84c085b550> , name= n
compare sees: <gast.gast.Name object at 0x7f84c085b780> , name= n

Is there any way I can make it use the symbol table and give me the same object for the same symbol? (Not just for the name objects, but for others too)

Edit: Using gast (not ast). But with ast also, similar behaviour is observed (each use is a new object). Full code to generate this:

import gast as ast
code = '''
def foo(n:int)->int:
  if n > 0:
    return 1
  elif n < 0:
    return -1
  else:
    return 0
'''
module = ast.parse(code)

class Visitor(ast.NodeVisitor):
  def visit_FunctionDef(self, node):
    print("function arg:", node.args.args[0], ", name=", node.args.args[0].id)
    for stmt in node.body:
      self.visit(stmt)
  def visit_Compare(self, node):
    print("compare sees:", node.left, ", name=", node.left.id)

Visitor().visit(module)
0 Answers
Related