在 python 中不使用 ast.parse 从组成元素生成 ast [英] Generate ast from constituent elements without using ast.parse in python

查看:31
本文介绍了在 python 中不使用 ast.parse 从组成元素生成 ast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 python ast 模块,可以生成一个简单的抽象语法树,如下所示:

导入 ast模块 = ast.parse('x=3')

这会生成一个 Module 对象,可以使用 astor 库检索其源代码,如下所示:

导入 astorastor.to_source(模块)

生成输出

'x = 3\n'

是否有可能在不使用ast.parse方法的情况下,从其组成元素构成完全相同的模块对象,使得astor.to_source方法可以生成相同的源代码?如果是这样怎么办?

解决方案

我想我刚刚找到它.使用 ast.dump 可以检查树的内容如下:

导入 astor, ast模块 = ast.parse('x=3')ast.dump(模块)

这会产生以下显示底层结构的输出:

"Module(body=[Assign(targets=[Name(id='x', ctx=Store())], value=Num(n=3))])"

我们可以利用这些信息从头开始构建相同的树,然后使用astor来恢复源:

module = ast.Module(body=[ast.Assign(targets=[ast.Name(id='x', ctx=ast.Store())], value=ast.Num(n=3))])astor.to_source(模块)

输出以下内容:

'x = 3\n'

但是有一个问题,因为执行这个新树会导致一个错误:

exec(compile(module, filename='<ast>', mode="exec"))

<块引用>

回溯(最近一次调用最后一次):文件",第 1 行,在类型错误:stmt 中缺少必填字段lineno"

要解决此问题,必须使用 ast.fix_missing_locations 方法将行号添加到每个节点.

Using the python ast module, it is possible to generate a simple abstract syntax tree as follows:

import ast
module = ast.parse('x=3')

This generates a Module object for which the source code can be retrieved using the astor library as follows:

import astor
astor.to_source(module)

Generating an output of

'x = 3\n'

Is it possible to constitute the exact same module object from its constituent elements without using the ast.parse method such that the astor.to_source method can generate the same source code? if so how?

解决方案

I think I just found it. using ast.dump one can inspect the contents of the tree as follows:

import astor, ast
module = ast.parse('x=3')
ast.dump(module)

This results in the following output which reveals the underlying structure:

"Module(body=[Assign(targets=[Name(id='x', ctx=Store())], value=Num(n=3))])"

We can make use of this information to build the same tree from scratch, and then use astor to recover the source:

module = ast.Module(body=[ast.Assign(targets=[ast.Name(id='x', ctx=ast.Store())], value=ast.Num(n=3))])
astor.to_source(module)

Which outputs the following:

'x = 3\n'

There is one problem however, since executing this new tree results in an error:

exec(compile(module, filename='<ast>', mode="exec"))

Traceback (most recent call last): File "", line 1, in TypeError: required field "lineno" missing from stmt

To fix this, line numbers must be added to each node using the ast.fix_missing_locations method.

这篇关于在 python 中不使用 ast.parse 从组成元素生成 ast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆