使用符号的作用域注释Python AST。
项目描述
ast_scope
此包是Python词法作用域规则的实现。其接口简单,您只需将AST对象传递给annotate
函数,它就会提供从表示符号的树中的每个节点到包含作用域的映射。
示例用法:获取全局符号
假设你有以下代码
code = """
def f():
x = 3
lambda z: theta
return x + y
"""
并且你想要确定它引用了哪些全局变量。你只需要执行以下操作
import ast
import ast_scope
tree = ast.parse(code)
scope_info = ast_scope.annotate(tree)
global_variables = sorted(scope_info.global_scope.symbols_in_frame)
执行此代码后,global_variables
将绑定到['f', 'theta', 'y']
。
示例用法:获取依赖图
假设你有以下代码
code = """
def hailstone(n):
if n == 1:
return 1
if n % 2 == 0:
return hailstone(n // 2)
if n % 2 == 1:
return hailstone(3 * n + 1)
def mapper(f, lst):
return list(map(f, lst))
def lrange(n):
return list(range(n))
def main():
return mapper(hailstone, lrange(20))
"""
并且你想要找到依赖图。你可以运行以下操作
import ast
import ast_scope
tree = ast.parse(code)
scope_info = ast_scope.annotate(tree)
graph = scope_info.static_dependency_graph
这将得到以下顶级函数之间的依赖关系有向图(使用networkx渲染)
请参阅文档以了解注意事项。
示例用法:查找特定符号的作用域
以下代码
code = """
def f(x):
def g(x): return x()
return g(lambda: x)
"""
首先,解析代码并识别节点(在实际操作中,你可能总是这样做)。
import ast, ast_scope
tree = ast.parse(code)
last_x = tree.body[0].body[-1].value.args[0].body
如果你想找到最后一个x
可找到的作用域,只需运行注释器并查找其作用域!
# run the annotator
scope_info = ast_scope.annotate(tree)
scope_x = scope_info[last_x]
你应该得到一个包含作用域中其他变量、等信息的大量信息的FunctionScope
对象,但还有一个scope_x.function_node
,它是指向包含def
语句的f
的节点的指针。
项目详情
关闭
ast_scope-0.4.4.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | f61ca6f9fe46ca5843f8b33f48c1956fe25fdf4ad30d178fff9c70bfdf78c463 |
|
MD5 | 9b8099bab8ff89d61f29444edae34ed6 |
|
BLAKE2b-256 | c5d68482fa460a43d045913d52b382f08236780c66cffca353df7a9a9e2ab3a3 |