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.
pip install libcstVerified import paths — ran on the pinned version, not inferred.
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.
Ensure your environment is set up to use the default native parser. If you encounter parsing issues or rely on the old parser, update your setup to use the native implementation. Install with pre-built binary wheels when possible to avoid Rust toolchain dependencies.
Always return `updated_node` (or a modified copy of it) from `leave_` methods in `CSTTransformer`. Utilize `with_changes()` for modifying existing nodes and `FlattenSentinel` for inserting or removing multiple nodes to preserve formatting. Avoid `isinstance` for traversal; prefer visitor methods like `visit_<NodeType>` or matchers.
The easiest way to install Rust is via `rustup`. If you frequently build Python packages with native extensions, consider using an environment where Rust is pre-configured.
Consider using `sys.modules` checks at runtime to prevent co-installation, or implement a build-time script using a LibCST transformer to rewrite internal import paths in your fork. Explicitly declare conflicts in `pyproject.toml` if such a feature becomes available in package managers.
Use `from libcst.tool import dump` and then `print(dump(tree))` for a more concise and readable representation of the CST's essential elements, which is often more useful for understanding the tree's structure.
Install the library using pip: `pip install libcst`
Ensure the input code is valid Python for the target version, upgrade `libcst` to a version that supports the syntax, or use `libcst.parse_module()` for full modules.
Ensure you have a compatible Rust toolchain installed (e.g., `rustup install stable` if using `rustup`) or use a Python version for which `libcst` provides prebuilt wheels, or explicitly install a `libcst` version compatible with your Python interpreter.
Access `code_for_node` through the `Module` object from which the node was parsed: `module.code_for_node(your_cst_node)`.