问题
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