symtable — Access to the compiler’s symbol tables

Вихідний код: Lib/symtable.py


Таблиці символів генеруються компілятором з AST безпосередньо перед генерацією байт-коду. Таблиця символів відповідає за обчислення області кожного ідентифікатора в коді. symtable надає інтерфейс для перевірки цих таблиць.

Створення таблиць символів

symtable.symtable(code, filename, compile_type)

Повертає верхній рівень SymbolTable для вихідного коду Python. filename — це ім’я файлу, що містить код. compile_type схожий на аргумент mode для compile().

Вивчення таблиць символів

class symtable.SymbolTableType

An enumeration indicating the type of a SymbolTable object.

MODULE = "module"

Used for the symbol table of a module.

FUNCTION = "function"

Used for the symbol table of a function.

CLASS = "class"

Used for the symbol table of a class.

The following members refer to different flavors of annotation scopes.

ANNOTATION = "annotation"

Used for annotations if from __future__ import annotations is active.

TYPE_ALIAS = "type alias"

Used for the symbol table of type constructions.

TYPE_PARAMETERS = "type parameters"

Used for the symbol table of generic functions or generic classes.

TYPE_VARIABLE = "type variable"

Used for the symbol table of the bound, the constraint tuple or the default value of a single type variable in the formal sense, i.e., a TypeVar, a TypeVarTuple or a ParamSpec object (the latter two do not support a bound or a constraint tuple).

Added in version 3.13.

class symtable.SymbolTable

Таблиця простору імен для блоку. Конструктор не є публічним.

get_type()

Return the type of the symbol table. Possible values are members of the SymbolTableType enumeration.

Змінено в версії 3.12: Added 'annotation', 'TypeVar bound', 'type alias', and 'type parameter' as possible return values.

Змінено в версії 3.13: Return values are members of the SymbolTableType enumeration.

The exact values of the returned string may change in the future, and thus, it is recommended to use SymbolTableType members instead of hard-coded strings.

get_id()

Повернути ідентифікатор таблиці.

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'). For type parameter scopes (which are used for generic classes, functions, and type aliases), it is the name of the underlying class, function, or type alias. For type alias scopes, it is the name of the type alias. For TypeVar bound scopes, it is the name of the TypeVar.

get_lineno()

Повертає номер першого рядка в блоці, який представляє ця таблиця.

is_optimized()

Повертає True, якщо локальні значення в цій таблиці можна оптимізувати.

is_nested()

Повертає True, якщо блок є вкладеним класом або функцією.

has_children()

Повертає True, якщо в блоці є вкладені простори імен. Їх можна отримати за допомогою get_children().

get_identifiers()

Повертає об’єкт представлення, що містить імена символів у таблиці. Перегляньте документацію об’єктів перегляду.

lookup(name)

Знайдіть name у таблиці та поверніть екземпляр Symbol.

get_symbols()

Повертає список екземплярів Symbol для імен у таблиці.

get_children()

Повертає список вкладених таблиць символів.

class symtable.Function

A namespace for a function or method. This class inherits from SymbolTable.

get_parameters()

Повертає кортеж, що містить імена параметрів цієї функції.

get_locals()

Повертає кортеж, що містить імена місцевих жителів у цій функції.

get_globals()

Повертає кортеж, що містить імена глобалів у цій функції.

get_nonlocals()

Повертає кортеж, що містить імена нелокальних у цій функції.

get_frees()

Повертає кортеж, що містить імена вільних змінних у цій функції.

class symtable.Class

A namespace of a class. This class inherits from SymbolTable.

get_methods()

Return a tuple containing the names of method-like functions declared in the class.

Here, the term „method“ designates any function defined in the class body via def or async def.

Functions defined in a deeper scope (e.g., in an inner class) are not picked up by get_methods().

Наприклад:

>>> import symtable
>>> st = symtable.symtable('''
... def outer(): pass
...
... class A:
...    def f():
...        def w(): pass
...
...    def g(self): pass
...
...    @classmethod
...    async def h(cls): pass
...
...    global outer
...    def outer(self): pass
... ''', 'test', 'exec')
>>> class_A = st.get_children()[2]
>>> class_A.get_methods()
('f', 'g', 'h')

Although A().f() raises TypeError at runtime, A.f is still considered as a method-like function.

Deprecated since version 3.14, will be removed in version 3.16.

class symtable.Symbol

Запис у SymbolTable, що відповідає ідентифікатору в джерелі. Конструктор не є публічним.

get_name()

Повернути назву символу.

is_referenced()

Повертає True, якщо символ використовується в його блоці.

is_imported()

Повертає True, якщо символ створено з оператора імпорту.

is_parameter()

Повертає True, якщо символ є параметром.

is_type_parameter()

Return True if the symbol is a type parameter.

Added in version 3.14.0a0 (unreleased).

is_global()

Повертає True, якщо символ є глобальним.

is_nonlocal()

Повертає True, якщо символ нелокальний.

is_declared_global()

Повертає True, якщо символ оголошено глобальним за допомогою глобального оператора.

is_local()

Повертає True, якщо символ є локальним для свого блоку.

is_annotated()

Повертає True, якщо символ анотований.

Added in version 3.6.

is_free()

Повертає True, якщо символ є посиланням у його блоці, але не призначений.

is_free_class()

Return True if a class-scoped symbol is free from the perspective of a method.

Consider the following example:

def f():
    x = 1  # function-scoped
    class C:
        x = 2  # class-scoped
        def method(self):
            return x

In this example, the class-scoped symbol x is considered to be free from the perspective of C.method, thereby allowing the latter to return 1 at runtime and not 2.

Added in version 3.14.0a0 (unreleased).

is_assigned()

Повертає True, якщо символу призначено в його блоці.

is_comp_iter()

Return True if the symbol is a comprehension iteration variable.

Added in version 3.14.0a0 (unreleased).

is_comp_cell()

Return True if the symbol is a cell in an inlined comprehension.

Added in version 3.14.0a0 (unreleased).

is_namespace()

Повертає True, якщо зв’язування імен створює новий простір імен.

Якщо ім’я використовується як ціль оператора функції чи класу, це буде вірно.

Наприклад:

>>> table = symtable.symtable("def some_func(): pass", "string", "exec")
>>> table.lookup("some_func").is_namespace()
True

Зауважте, що одне ім’я може бути прив’язане до кількох об’єктів. Якщо результат True, ім’я також може бути прив’язане до інших об’єктів, таких як int або список, які не вводять новий простір імен.

get_namespaces()

Повертає список просторів імен, прив’язаних до цього імені.

get_namespace()

Return the namespace bound to this name. If more than one or no namespace is bound to this name, a ValueError is raised.

Використання командного рядка

Added in version 3.13.

The symtable module can be executed as a script from the command line.

python -m symtable [infile...]

Symbol tables are generated for the specified Python source files and dumped to stdout. If no input file is specified, the content is read from stdin.