LibCST

1.8.6 · active · verified Sun Mar 29

LibCST (Concrete Syntax Tree) is a Python library that parses Python 3.0 through 3.14 source code into a CST tree, preserving all formatting details like comments, whitespaces, and parentheses. It offers a compromise between an Abstract Syntax Tree (AST) and a traditional CST, designed for building automated refactoring (codemod) applications and linters. The current version is 1.8.6, and it maintains an active release cadence with frequent updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates parsing Python code, applying a `CSTTransformer` to modify a variable name (`old_var` to `new_var`), and then generating the modified code. It also shows how to use `libcst.tool.dump` for a concise representation of the CST and how to incorporate metadata providers.

import libcst as cst
from libcst import CSTTransformer, parse_module
from libcst.tool import dump # For pretty-printing the CST
from libcst.metadata import MetadataWrapper, QualifiedNameProvider

class MyTransformer(CSTTransformer):
    METADATA_DEPENDENCIES = {QualifiedNameProvider}

    def leave_Name(self, original_node, updated_node):
        # Example: change all instances of 'old_var' to 'new_var'
        if updated_node.value == 'old_var':
            print(f"Changing '{original_node.value}' to 'new_var' at {self.get_metadata(QualifiedNameProvider, original_node)}")
            return updated_node.with_changes(value='new_var')
        return updated_node


source_code = """
import os

def my_function(old_var):
    x = old_var + 1
    return x

old_var = 10
"""

# Parse the module into a CST
tree = parse_module(source_code)

# Wrap the tree with metadata providers
wrapper = MetadataWrapper(tree)

# Apply the transformer
modified_tree = wrapper.visit(MyTransformer())

# Generate the modified code
modified_code = modified_tree.code

print("Original Code:\n" + source_code)
print("\nModified Code:\n" + modified_code)
print("\nCST of Modified Code (dump):\n" + dump(modified_tree))

view raw JSON →