Search code examples
pythonabstract-syntax-treelibcst

How can I get a global variable's assigned value in libcst?


I want to parse the following Python file in libcst:

MY_VAR = "my_val"

def my_func(arg):
  # ...

my_func(MY_VAR)

Using libcst I'm able to get the "MY_VAR" as a string:

with open(pipeline_file_path, "r") as f:
    src_tree: cst.Module = cst.parse_module(f.read())
    wrapper = cst.metadata.MetadataWrapper(src_tree)

    scopes = set(wrapper.resolve(cst.metadata.ScopeProvider).values())
    for scope in scopes:
        for assignment in scope.assignments:
            if isinstance(assignment, cst.metadata.Assignment):
                node = assignment.node
                print(assignment.node.value) # prints MY_VAR

But I want the right side of the assignment; how can I print "my_val"?


Solution

  • Barmar's comment is the correct answer, here's my CSTVisitor code:

    def on_leave(self, node):
        if isinstance(node, cst.Assign):
            left = None
            right = None
            for child in node.children:
                if isinstance(child, cst.AssignTarget):
                    left = child.target.value
                elif isinstance(child, cst.SimpleString):
                    right = child.evaluated_value
    
            if left and right:
                self.globals[left] = right