没有项目描述

scoping-resolver的Python项目详细描述


关于

这个repo带来了对python语言范围的强大分析, 它可以告诉上下文中的符号是freevarbounded varcell var,以及许多其他细节 比如,“这个闭包是一个协程/生成器/异步生成器吗?”等等。

有关python作用域的更多信息,请检查code object

Symbol-Resolver可以用来实现从python到另一种具有卫生作用域的语言的transpiler, 比如Tensorflow AutoGraphNumba 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团队仍在努力解决上述问题,您可以在以下链接中找到不卫生的内容:

https://github.com/tensorflow/tensorflow/blob/3ae375aa92fbb6155f82393735d0b98d8fb9c1b2/tensorflow/python/autograph/converters/lists.py#L129

用法

检查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)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
如何从java中链接到数组的数组中删除值。jar文件?   性能记录屏幕Java磁盘速度   java Elastic APM Tomcat zip文件或JAR清单丢失   java无法在eclipse控制台上打印结果   java如何在Android中解析json对象?   java如何更改边缘根类型   java根据一些规则替换EditText中的字母   java项目反应器:是否有类似Nosideeffect finally的方法(不是sideeffect方法doFinally)   java连接Cassandra节点和spark   开源Java作业调度器:远程处理、负载平衡、故障切换、依赖DAG?   使用矢量汇编程序(Java)在Spark中设置输入和输出时出现问题   swing如何在Java中为文本字段创建右键单击菜单?   java查找最近的邻居/纬度和经度   java计算完成的数独板的行和列