On this page
  1. symtable
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Walking All Nested Scopes
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

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

Common Functions

Classes & Objects

Linked from

Related notes