symtable — 访问编译器的符号表¶
符号表是由编译器在生成字节码之前从 AST 生成的。符号表负责计算代码中每个标识符的范围。symtable 提供一个接口来检查这些表。
生成符号表¶
- symtable.symtable(code, filename, compile_type)¶
返回 Python 源码的顶层
SymbolTable。filename 是包含代码的文件的名称。compile_type 就像compile()的 mode 参数。
审查符号表¶
- class symtable.SymbolTable¶
一个区块的命名空间表。构造函数是不公开的。
- get_type()¶
返回符号表的类型。可能的值是
'class'、'module'和'function'。
- get_id()¶
返回该表的标识符。
- get_name()¶
返回表的名称。如果该表是为一个类准备的,这就是类的名称;如果该表是为一个函数准备的,这就是函数的名称;如果该表是全局的,这就是
'top'(get_type()返回'module')。
- get_lineno()¶
返回该表所代表的区块中第一行的编号。
- is_optimized()¶
如果此表中的 locals 可以被优化,返回
True。
- is_nested()¶
如果该块是一个嵌套的类或函数,则返回
True。
- has_children()¶
如果该区块内有嵌套的命名空间,返回
True。这些可以通过get_children()来获得。
- get_identifiers()¶
Return a view object containing the names of symbols in the table. See the documentation of view objects.
- get_children()¶
返回一个嵌套符号表的列表。
- class symtable.Function¶
一个函数或方法的命名空间。该类继承于
SymbolTable。- get_parameters()¶
返回一个包含该函数参数名称的元组。
- get_locals()¶
返回一个包含本函数中 locals 名称的元组。
- get_globals()¶
返回一个包含此函数中 globals 名称的元组。
- get_nonlocals()¶
返回一个包含本函数中的 nonlocals 名称的元组。
- get_frees()¶
返回一个包含本函数中自由变量名称的元组。
- class symtable.Class¶
一个类的命名空间。该类继承于
SymbolTable。- get_methods()¶
返回一个包含在该类中声明的方法名称的元组。
- class symtable.Symbol¶
SymbolTable中的一个条目,对应于源中的一个标识符。该构造函数不是公开的。- get_name()¶
Return the symbol’s name.
- is_referenced()¶
Return
Trueif the symbol is used in its block.
- is_imported()¶
Return
Trueif the symbol is created from an import statement.
- is_parameter()¶
Return
Trueif the symbol is a parameter.
- is_global()¶
Return
Trueif the symbol is global.
- is_nonlocal()¶
Return
Trueif the symbol is nonlocal.
- is_declared_global()¶
Return
Trueif the symbol is declared global with a global statement.
- is_local()¶
Return
Trueif the symbol is local to its block.
- is_annotated()¶
Return
Trueif the symbol is annotated.3.6 新版功能.
- is_free()¶
Return
Trueif the symbol is referenced in its block, but not assigned to.
- is_assigned()¶
Return
Trueif the symbol is assigned to in its block.
- is_namespace()¶
Return
Trueif name binding introduces new namespace.If the name is used as the target of a function or class statement, this will be true.
例如:
>>> 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_namespaces()¶
Return a list of namespaces bound to this name.
- get_namespace()¶
Return the namespace bound to this name. If more than one or no namespace is bound to this name, a
ValueErroris raised.