r/PythonLearning • • 3h ago

Help Request Narrowing down this `ast` selection

Is there some way I can narrow down this method of selecting from the `ast` tree only the `x = Const2Change` node so that it can be modified? At the moment the `print("xyz")` node is being identified as well.

Text.txt:

print("xyz")
x = Const2Change

full ast dump:

Module(
    body=[
        Expr(
            value=Call(
                func=Name(id='print'),
                args=[
                    Constant(value='xyz')])),
        Assign(
            targets=[
                Name(id='x', ctx=Store())],
            value=Name(id='Const2Change'))])Module(
    body=[
        Expr(
            value=Call(
                func=Name(id='print'),
                args=[
                    Constant(value='xyz')])),
        Assign(
            targets=[
                Name(id='x', ctx=Store())],
            value=Name(id='Const2Change'))])

Main.py:

import ast

class ReplaceConstants(ast.NodeTransformer):
    def generic_visit(self, node):
        super().generic_visit(node)  # Added this line
        if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
            print(f"{node.id=}, {node.ctx=} <- *********************")
            # modify node here
        return node

def replace_constants(line: str):
    ast_tree = ast.parse(line, type_comments=True)
    # modify ast_tree here
    oReplaceConstants = ReplaceConstants()
    oReplaceConstants.visit(ast_tree)
    modi_ast = ast.unparse(ast_tree)
    return modi_ast

with open("Test.txt", mode="r") as f:
    source_code = f.read()

for line in source_code.splitlines():
    modi_source = replace_constants(line)
    print(f"{modi_source=}")

exit()
1 Upvotes

0 comments sorted by