Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example to insert python code through AST #206

Open
hshen14 opened this issue Jan 8, 2022 · 1 comment
Open

Example to insert python code through AST #206

hshen14 opened this issue Jan 8, 2022 · 1 comment

Comments

@hshen14
Copy link

hshen14 commented Jan 8, 2022

Hi,

Is there any example to show how to insert python code automatically through AST?

Thanks.

@berkerpeksag
Copy link
Owner

Here's a quick and dirty example:

import ast
import astor

def add_new_argument_to_function(node, name):
    node.args.args.append(ast.arg(arg=name, annotation=None))
    for body_node in node.body:
        if isinstance(body_node, ast.Return):
            elts = [
                # We assume ast.Name.
                body_node.value,
                ast.Name(id=name, ctx=ast.Load()),
            ]
            body_node.value = ast.Tuple(elts=elts, ctx=ast.Load())
    return node

name = "foo"
source = f"""
def {name}(a):
    return a
"""

tree = ast.parse(source)

for i, node in enumerate(tree.body):
    if isinstance(node, ast.FunctionDef) and node.name == name:
        tree.body[i] = add_new_argument_to_function(node, "b")

print(astor.to_source(tree))

This will print:

def foo(a, b):
    return a, b

I think it would be nice to add this one and a couple more examples to the documentation. Patches welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants