用ast重写代码;python

2024-09-27 09:33:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习AST,它似乎是一个强大的东西,但我不明白代码去了哪里,为什么会消失。说我想重写

example = """def fake(x):\n
    y = ['useless list']\n
    return x
"""

作为

^{pr2}$

我看不出用这种方式重写的方法。我甚至找不到一种方法来获取这行文字:

In [1]: example = """def fake(x):\n
   ...:     y = ['useless list']\n
   ...:     return x
   ...: """

In [3]: import ast

In [4]: p = ast.parse(example)

In [5]: p
Out[5]: <_ast.Module at 0x7f22f7274a10>

In [6]: p.body
Out[6]: [<_ast.FunctionDef at 0x7f22f7274a50>]

In [7]: p.body
Out[7]: [<_ast.FunctionDef at 0x7f22f7274a50>]

In [8]: f = p.body[0]

In [9]: f
Out[9]: <_ast.FunctionDef at 0x7f22f7274a50>

In [10]: f.body
Out[10]: [<_ast.Assign at 0x7f22f7274b10>, <_ast.Return at 0x7f22f7274c10>]

In [11]: f.name
Out[11]: 'fake'

In [12]: newf = f.body[1:]

In [13]: newf
Out[13]: [<_ast.Return at 0x7f22f7274c10>]

In [14]: z = newf[0]

In [15]: z.value
Out[15]: <_ast.Name at 0x7f22f7274c50>

In [16]: z.value.id
Out[16]: 'x'

更令人惊讶的是,它给你的是开始的行号,而不是结尾。所以你知道一个函数从哪里开始,但不知道它在哪里结束,这是没有用的

在没有列表y的情况下,如何获取代码并重写此函数?谢谢你


Tags: 方法代码inreturnexampledefbodyout
2条回答

也许这会对你有所帮助:

import ast
import astor

example = """
def fake(x):
    y = ['useless list']
    return x
"""

tree = ast.parse(example)

# iterating through list which is represents function on ast
for ind, item in enumerate(tree.body[0].body):
    if isinstance(item, ast.Assign) and isinstance(item.value, ast.List):
        del tree.body[0].body[ind]
        break

print astor.to_source(tree)

更好地使用更多OOP:

^{pr2}$

使用RedBaron Full Syntax Tree:更好

from redbaron import RedBaron

example = """
def fake(x):
    y = ['useless list']
    return x
"""
red = RedBaron(example)
methods = red.find_all('DefNode').data
for data in methods:
    if len(data.value.data) > 0:
        for vals in data.value.data:
            if vals[0].type == 'assignment' and vals[0].value.type == 'list':
                index = vals[0].index_on_parent
                par = vals[0].parent
                del par[index]
                break

print red.dumps()

现在有一个库可以告诉您每个节点的确切文本范围:ASTTokens。下面是你的例子:

import ast, asttokens
atok = asttokens.ASTTokens(example, parse=True)

for node in ast.walk(atok.tree):
  if hasattr(node, 'lineno'):
    print atok.get_text_range(node), node.__class__.__name__, atok.get_text(node)

这将产生以下输出(注意文本中的位置):

^{pr2}$

相关问题 更多 >

    热门问题