On this page
symtable — Access to the compiler’s symbol tables
Source code: Lib/symtable.py
Symbol tables are generated by the compiler from AST just before bytecode is generated. The symbol table is responsible for calculating the scope of every identifier in the code. symtable
provides an interface to examine these tables.
Generating Symbol Tables
symtable.
symtable
( code, filename, compile_type )-
Return the toplevel
SymbolTable
for the Python source code. filename is the name of the file containing the code. compile_type is like the mode argument tocompile()
.
Examining Symbol Tables
- class
symtable.
SymbolTable
-
A namespace table for a block. The constructor is not public.
get_type
( )-
Return the type of the symbol table. Possible values are
'class'
,'module'
, and'function'
.
get_name
( )-
Return the table’s name. This is the name of the class if the table is for a class, the name of the function if the table is for a function, or
'top'
if the table is global (get_type()
returns'module'
).
has_children
( )-
Return
True
if the block has nested namespaces within it. These can be obtained withget_children()
.
lookup
( name )-
Lookup name in the table and return a
Symbol
instance.
get_symbols
( )-
Return a list of
Symbol
instances for names in the table.
- class
symtable.
Function
-
A namespace for a function or method. This class inherits
SymbolTable
.
- class
symtable.
Class
-
A namespace of a class. This class inherits
SymbolTable
.
- class
symtable.
Symbol
-
An entry in a
SymbolTable
corresponding to an identifier in the source. The constructor is not public.is_namespace
( )-
Return
True
if name binding introduces new namespace.If the name is used as the target of a function or class statement, this will be true.
For example:
>>> table = symtable.symtable("def some_func(): pass", "string", "exec") >>> table.lookup("some_func").is_namespace() True
Note that a single name can be bound to multiple objects. If the result is
True
, the name may also be bound to other objects, like an int or list, that does not introduce a new namespace.
get_namespace
( )-
Return the namespace bound to this name. If more than one namespace is bound,
ValueError
is raised.