On this page
symtable
Prev: subprocess | Up: stdlib_module | Next: sys
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — symtable
Tags: #public #python3 #stdlib
Import
import symtable
Overview
Interface to Python's compiler symbol tables (symtable.symtable()), exposing exact lexical scopes (module, class, function, comprehension) and how every identifier is bound (is_local(), is_global(), is_free(), is_parameter(), is_imported()). Use symtable when building linters, refactoring tools, or static analyzers instead of re-implementing Python's scoping rules on top of ast.
Quick Start
import symtable
code = """
TOTAL = 10
def make_adder(x):
def add(y):
return x + y + TOTAL
return add
"""
table = symtable.symtable(code, "<string>", "exec")
make_adder = table.get_children()[0]
add_fn = make_adder.get_children()[0]
assert add_fn.lookup("y").is_parameter()
assert add_fn.lookup("x").is_free() # captured closure variable
assert add_fn.lookup("TOTAL").is_global()
Implementation Walkthrough
1. Walking All Nested Scopes
Recurse through get_children() to audit every scope's local, free, and global variables:
import symtable
def dump_scopes(tbl: symtable.SymbolTable) -> dict[str, list[str]]:
out = {tbl.get_name(): sorted(tbl.get_identifiers())}
for child in tbl.get_children():
out.update(dump_scopes(child))
return out
scopes = dump_scopes(symtable.symtable("def f(a): b = a + 1", "<mem>", "exec"))
assert scopes["f"] == ["a", "b"]
Gotchas & Boundaries
- Compile-time lexical analysis only:
symtablesees declared scopes and bindings, not runtime monkey-patching,exec(), or dynamicglobals()mutations. - Function-specific methods: Methods like
get_parameters(),get_locals(),get_frees(), andget_globals()exist onFunctionsymbol tables (checktbl.get_type() == "function"), not on module or class tables. - Pair with ast for source locations:
symtablegives scope semantics andget_lineno(), while ast gives exact node positions and syntax structure.
Common Functions
- symtable.symtable() —
symtable(code, filename, compile_type)— Return the toplevel SymbolTable for the source code.
Classes & Objects
- symtable.Class —
symtable.Classclass. (Methods:.get_children(),.get_id(),.get_identifiers(),.get_lineno(),.get_methods(),.get_name()) - symtable.Function —
symtable.Functionclass. (Methods:.get_children(),.get_frees(),.get_globals(),.get_id(),.get_identifiers(),.get_lineno()) - symtable.Symbol —
symtable.Symbolclass. (Methods:.get_name(),.get_namespace(),.get_namespaces(),.is_annotated(),.is_assigned(),.is_comp_cell()) - symtable.SymbolTable —
symtable.SymbolTableclass. (Methods:.get_children(),.get_id(),.get_identifiers(),.get_lineno(),.get_name(),.get_symbols()) - symtable.SymbolTableType —
symtable.SymbolTableTypeclass. (Methods:.capitalize(),.casefold(),.center(),.count(),.encode(),.endswith())
Linked from
Related notes
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/subprocess Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/sys Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/ast Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/builtins Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/symtable/Class Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/symtable/Function Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/symtable/Symbol Linked here; shared tags: #stdlib