没有项目描述

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新手   java当我更改ImageButton图像时,不会实时更改   不尊重XML中按钮的安卓换行符,但它使用Java代码   java签署gradle插件   java如何在Launch4j中添加VM参数   通过ObjectOutputStream发送文件,然后用Java保存?   基于注释的web中的java DispatcherServlet配置。xml   java根据点击数对2D数组进行排序   java HSQLDB能处理数百万行吗?   ejb3.0 java ejb3@PostConstruct   java如何在WebSpherePortal8.0中应用主题更改?   如何配置java重启库以不重用cookie   java错误:表达式的开头非法,后跟PriorityQueue   java如何更新RecyclerView的数据集并从视图持有者处通知适配器?