python - 用ast重写代码; Python

标签 python python-2.7 data-structures abstract-syntax-tree

我正在学习 AST,它似乎是一个强大的东西,但我很困惑代码去了哪里以及为什么它消失了。说我想重写

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

作为

example = """def fake(x):\n
    return x
"""

我看不到任何以这种方式重写的方法。我什至找不到获取该行文本的方法:

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 的情况下获取代码并重写此函数?谢谢

最佳答案

也许这会对您有所帮助:

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:

class RemoveList(ast.NodeTransformer):
    def visit_FunctionDef(self, node):
        self.generic_visit(node)
        for leaf in node.body:
            if isinstance(leaf, ast.Assign) and isinstance(leaf.value, ast.List):
                del node.body[node.body.index(leaf)]
        ast.fix_missing_locations(node)
        return node


tree_class = ast.parse(example)
remove_list = RemoveList().visit(tree_class)
print astor.to_source(tree_class)

使用 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()

关于python - 用ast重写代码; Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36022935/

相关文章:

python - Spyder、matplotlib 和 prints 中的子进程不起作用

python - 如何在python中获取矩阵?

python - 无法在 Python 上准确计算圆周率

c - 当指向前一个节点的指针不可用时从单个链表中删除中间节点

c - 链表在打印时仅显示第一个节点元素

python - 带有惰性字典的 str.format()?

python - 在sqlalchemy中,当子表有多个父表的外键时,如何使用多态连接表继承?

python - PyQt 重载预先存在的信号

mysql - 如何在 Django 中创建映射表?

Java数据结构,一个以value里面的对象为key的map