transform python code programmatically via meta package

那年仲夏 提交于 2020-01-25 02:51:08

问题


I'd like to transform all occurrences of "some_func(a, b)" in a python module to "assert a == b". I tried with meta package:

import meta, ast

source = '''
assert_equal(a, b)
'''
orig = ast.parse(source, '<nofile>', 'exec')

assert_ast = ast.parse('assert a == b')
assert_ast.body[0].test.left = orig.body[0].value.args[0]
assert_ast.body[0].test.comparators[0] = orig.body[0].value.args[1]

code = compile(assert_ast, '<nofile>', 'exec')
mod2 = meta.decompile(code)
source2 = meta.dump_python_source(mod2)

print(source2)

This prints "((a == b) or raise AssertionError)", not quite what I was expecting but indeed semantically equivalent to what I want. I can apply a regex sub to "fix" this:

source3 = re.sub(r"\(\((.*)\) or raise AssertionError\)", r"assert \1", source2)
print(source3)

So far so good, I should be able to use NodeTransformer to apply this to all occurrences of some_func. However I was wondering if there is a way of fixing the above meta-based approach so that I don't have to use any regex post-processing?

来源:https://stackoverflow.com/questions/34848548/transform-python-code-programmatically-via-meta-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!