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?
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?
You will likely enjoy Eli Bendersky's write up on the topic here
In CPython, you have the
symtable
module available to you.In part 2, Eli describes a method which walks the symbol table that is incredibly helpful:
Python is dynamic rather than static in nature. Rather than a symbol table as in compiled object code, the virtual machine has an addressible namespace for your variables.
The
dir()
ordir(module)
function returns the effective namespace at that point in the code. It's mainly used in the interactive interpreter but can be used by code as well. It returns a list of strings, each of which is a variable with some value.The
globals()
function returns a dictionary of variable names to variable values, where the variable names are considered global in scope at that moment.The
locals()
function returns a dictionary of variable names to variable values, where the variable names are considered local in scope at that moment.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:
Python does not make a symbol table before the program is executed. In fact, types and functions can be (and is normally) defined during the execution.
You may be interested in reading Why compile Python code?
Also see the detailed answer by @wberry