没有项目描述
scoping-resolver的Python项目详细描述
关于
这个repo带来了对python语言范围的强大分析,
它可以告诉上下文中的符号是freevar
、bounded var
或cell var
,以及许多其他细节
比如,“这个闭包是一个协程/生成器/异步生成器吗?”等等。
有关python作用域的更多信息,请检查code object。
Symbol-Resolver
可以用来实现从python到另一种具有卫生作用域的语言的transpiler,
比如Tensorflow AutoGraph和Numba AutoJit:
fromutranspilerimporttranspile,func# The `func` might not be a valid python function,# but it can be used to denote some external function.@transpiledefufunc(x):func(x)
在上面的代码中,func
被解析为一个global
变量,换句话说,
然后可以从当前模块的全局上下文中搜索名称func
,
并确保它正是期望的外部函数func
对象。
如果您仍然对symbol resolver的威力感到困惑,还有一个例子可以给您:
fromutranspilerimporttranspile,func@transpiledefufunc(x):func=lambdax:x+1func(x)
或
fromutranspilerimporttranspile,funcfunc=lambdax:x+1@transpiledefufunc(x):func(x)
现在您不能期望func
作为外部函数,但是您可能不希望通过实现
您的特定符号分析器。
TensorFlow团队仍在努力解决上述问题,您可以在以下链接中找到不卫生的内容:
用法
检查test/test_simple.py
。
ScopeTagger
将任何导致新上下文的ast转换为名为ScopedAst
的包装节点,其中
保存有关当前上下文的信息。
importunittestimportastfromscoping_resolverimportto_scoped_ast,ScopedAst,SymTable,ScopeTaggermod_code="""c = lambda x: xdef f(x): g(x) c = 2 g(c)"""classTestSimple(unittest.TestCase):deftest(self):mod=ast.parse(mod_code)# Make a new symbol table object for global context.# Of course, symbol tables for sub-contexts would be created# when analyzing the whole module AST.g=SymTable.global_context()# Get raw information of AST.ScopeTagger(g).visit(mod)# Peform analysis.g.analyze()# You can directly use `to_scoped_ast(mod)`# instead when you don't need a top level `g`.# Show representations of nested scopes:print(g.show_resolution())# [AnalyzedSymTable(bounds=set(), freevars=set(), cellvars=set()),# [[AnalyzedSymTable(bounds={'x'}, freevars=set(), cellvars=set()), []],# [AnalyzedSymTable(bounds={'x', 'c'}, freevars=set(), cellvars=set()), []]]]body=mod.bodydef_f:ScopedAst=body[1]# `FunctionDef` creates a new context, so it'll be wrapped inside a ScopedAstself.assertEqual(type(def_f),ScopedAst)self.assertEqual(type(def_f.node),ast.FunctionDef)self.assertIn('c',def_f.scope.analyzed.bounds)