Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7712575
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T01:39:58+00:00 2026-06-01T01:39:58+00:00

The following is a Python code snippet using the ast and symtable packages. I

  • 0

The following is a Python code snippet using the ast and symtable
packages. I am trying to parse the code and check the types. But I
don’t understand how to traverse objects to get to the actual variable
being referenced.

The following code implements a NodeVisitor, and a function is presented to the compiler and parsed by the compiler and the ast walked. The function being analyzed (eval_types) is passed a couple objects.

Below are the code chunks that make up the example. I have added some comments for each chunk. To run the code, the “chunks” need to be reassembled.

The imports and a function to un-indent a block of code for parsing.

import inspect
import ast
import symtable
from tokenize import generate_tokens, untokenize, INDENT
from cStringIO import StringIO

# _dedent borrowed from the myhdl package (www.myhdl.org)
def _dedent(s):
    """Dedent python code string."""

    result = [t[:2] for t in generate_tokens(StringIO(s).readline)]
    # set initial indent to 0 if any
    if result[0][0] == INDENT:
        result[0] = (INDENT, '')
    return untokenize(result)

The following is the node visitor, it has the generic unhandled and name visitor overloads.

class NodeVisitor(ast.NodeVisitor):
    def __init__(self, SymbolTable):
        self.symtable = SymbolTable
        for child in SymbolTable.get_children():
            self.symtable = child
            print(child.get_symbols())

    def _visit_children(self, node):
        """Determine if the node has children and visit"""
        for _, value in ast.iter_fields(node):
            if isinstance(value, list):
                for item in value:
                    if isinstance(item, ast.AST):
                        print('  visit item %s' % (type(item).__name__))
                        self.visit(item)

            elif isinstance(value, ast.AST):
                print('  visit value %s' % (type(value).__name__))
                self.visit(value)

    def generic_visit(self, node):
        print(type(node).__name__)
        self._visit_children(node)

    def visit_Name(self, node):
        print('  variable %s type %s' % (node.id,
                                         self.symtable.lookup(node.id)))
        print(dir(self.symtable.lookup(node.id)))

The following are some simple classes that will be used in the function that will be parsed and analyzed with the AST.

class MyObj(object):
    def __init__(self):
        self.val = None

class MyObjFloat(object):
    def __init__(self):
        self.x = 1.

class MyObjInt(object):
    def __init__(self):
        self.x = 1

class MyObjObj(object):
    def __init__(self):
        self.xi = MyObjInt()
        self.xf = MyObjFloat()

The following is the test function, the eval_types function is the function that will be analyzed with the AST.

def testFunc(x,y,xo,z):

    def eval_types():
        z.val = x + y + xo.xi.x + xo.xf.x

    return eval_types

The code to execute the example, compile the function and analyze.

if __name__ == '__main__':
    z = MyObj()
    print(z.val)
    f = testFunc(1, 2, MyObjObj(), z)
    f()
    print(z.val)
    s = inspect.getsource(f)
    s = _dedent(s)
    print(type(s))
    print(s)

    SymbolTable = symtable.symtable(s,'string','exec')
    tree = ast.parse(s)
    v = NodeVisitor(SymbolTable)
    v.visit(tree)

The following is an example output up to the first name visit.

Module
  visit item FunctionDef
FunctionDef
  visit value arguments
arguments
  visit item Assign
Assign
  visit item Attribute
Attribute
  visit value Name
  variable z type <symbol 'z'>
['_Symbol__flags', '_Symbol__name', '_Symbol__namespaces', 
 '_Symbol__scope', '__class__', '__delattr__', '__dict__', 
 '__doc__', '__format__', '__getattribute__', '__hash__', 
 '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', 
 '__repr__', '__setattr__', '__sizeof__', '__str__', 
 '__subclasshook__', '__weakref__', 'get_name', 'get_namespace', 
 'get_namespaces', 'is_assigned', 'is_declared_global', 
 'is_free', 'is_global', 'is_imported', 'is_local', 
 'is_namespace', 'is_parameter', 'is_referenced']

Creating the node visitor doesn’t seem to bad but I can’t figure out
how to traverse an object hierarchy. In the general case the variable
being accessed could be buried deep in a object. How to get to the actual variable being accessed from the ast visitor? I only see that an object is at the node but no additional information what the result variable access is.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T01:39:59+00:00Added an answer on June 1, 2026 at 1:39 am

    I don’t know if you’re still looking for this, but it looks like you just need to add a visit_Attribute and traverse backwards. If you add this to your example:

    def visit_Attribute(self, node):
        print('  attribute %s' % node.attr)
        self._visit_children(node)
    

    Then the output for xo.xf.x is:

    Add
      visit value Attribute
      attribute x
      visit value Attribute
      attribute xf
      visit value Name
      variable xo type <symbol 'xo'>
      visit value Load
    

    Depending what you want to do with this, you would just need to store the attributes in a list until a Name is encountered, then reverse them.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This following is a snippet of Python code I found that solves a mathematical
I have the following Python code: import xml.dom.minidom import xml.parsers.expat try: domTree = ml.dom.minidom.parse(myXMLFileName)
Is the following code snippet from a Python WSGI app safe from directory traversal?
I'm trying to parse a CSV file using Python's csv module (specifically, the DictReader
I am trying to get the correct Big-O of the following code snippet: s
I have opened a shelve using the following code: #!/usr/bin/python import shelve #Module:Shelve is
Consider the following snippet of Python code: from sqlalchemy import * from sqlalchemy.orm import
When running the following python code: >>> f = open(rmyfile.txt, a+) >>> f.seek(-1,2) >>>
I have the following Python code: cursor.execute("INSERT INTO table VALUES var1, var2, var3,") where
in the following python code: narg=len(sys.argv) print @length arg= , narg if narg ==

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.