用ast重写代码;蟒蛇 [英] rewriting code with ast; python

查看:115
本文介绍了用ast重写代码;蟒蛇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习AST,这似乎是一项强大的功能,但是我对代码的去向以及为什么消失感到困惑。假设我要重写

I am learning AST and it seems like a powerful thing but I'm confused where the code went and why it disappeared. Say I want to rewrite

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

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

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

I can't see any way to rewrite in this manner. I can't even find a way to get the text of the line:

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'

更令人惊讶的是,它如何为您提供开始的线号,而不是结束的线号。因此,您知道函数从何处开始,而不是从何处结束,这没有用

Even more surprising is how it gives you the lineno of the start, but not the end. So you know where a function begins, but not where it ends, which is of no use

我如何获取代码并重写此函数,而无需列出 y ?谢谢

How can I grab the code and rewrite this func without the list y? Thank you

推荐答案

也许会帮助您:

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:

Better using more 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完整语法树:

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

这篇关于用ast重写代码;蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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