How can we see the Symbol-Table of a python source code?
I mean, Python makes a symbol table for each program before actually running it. So my question is how can I get that symbol-table as output?
If you are asking about the symbol table that is used when generating bytecode, take a look at the symtable
module. Also, these two articles by Eli Bendersky are fascinating, and very detailed:
Python Internals: Symbol tables, part 1
Python Internals: Symbol tables, part 2
In part 2, he details a function that can print out a description of a symtable, but it seems to have been written for Python 3. Here's a version for Python 2.x:
def describe_symtable(st, recursive=True, indent=0):
def print_d(s, *args):
prefix = ' ' *indent
print prefix + s + ' ' + ' '.join(args)
print_d('Symtable: type=%s, id=%s, name=%s' % (
st.get_type(), st.get_id(), st.get_name()))
print_d(' nested:', str(st.is_nested()))
print_d(' has children:', str(st.has_children()))
print_d(' identifiers:', str(list(st.get_identifiers())))
if recursive:
for child_st in st.get_children():
describe_symtable(child_st, recursive, indent + 5)