Registry / testing / libcst

libcst

JSON →
library1.9.0pypypi✓ verified 26d ago

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 libcst
INSTALL
IMPORT
SIG · LIBCST
L
libcst
testingpythonv1.9.0
Install
2.3s avg
Import
634ms
Disk
32MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.9.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.672s · 32.5MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.3s · import 0.596s · 34MB
32MB installed
● package 32MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

libcst
import libcst as cst
CSTVisitor
from libcst import CSTVisitor
CSTTransformer
from libcst import CSTTransformer
parse_module
from libcst import parse_module
dump
from libcst.tool import dump
from libcst.display import dump
While `libcst.display.dump` was shown in older examples, `libcst.tool.dump` is the more consistent and often demonstrated path for displaying a concise CST representation.

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))
Debug
Known issues
breakingLibCST transitioned to a new, Rust-based parser by default in version 1.0.0. The old pure-Python parser, previously accessible via `LIBCST_PARSER_TYPE=pure` environment variable, is scheduled for removal in future non-patch releases.
fix
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.
affects: >=1.0.0
gotchaWhen programmatically modifying a CST, directly re-assigning nodes or performing in-place modifications can lead to unexpected loss of formatting (whitespace, comments). LibCST nodes are immutable.
fix
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.
affects: All versions
gotchaBuilding LibCST from source (e.g., if a binary wheel is not available for your specific Python version or OS architecture) requires a recent Rust toolchain, including `cargo`, to be installed and available in your PATH.
fix
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.
affects: All versions
gotchaForking and renaming a project that internally uses absolute imports from `libcst` can lead to conflicts if both the original `libcst` and your renamed fork are installed in the same environment.
fix
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.
affects: All versions
gotchaWhen debugging CST structures, simply `print(tree)` might provide an overwhelming amount of detail including all whitespace and token information.
fix
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.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'libcst'
The `libcst` library is not installed in the Python environment.
fix
Install the library using pip: `pip install libcst`
libcst._exceptions.ParserSyntaxError: Syntax Error @ X:Y. Incomplete input. Unexpectedly encountered '...'
The input source code contains invalid Python syntax or uses Python features not yet supported by the installed `libcst` version, or the wrong parsing function (`parse_expression` instead of `parse_module`) was used.
fix
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.
Exception: Logic error, unexpected top level type!
This error, often accompanied by Rust compilation messages, indicates compatibility issues between the `libcst` native parser (written in Rust) and the Python version or Rust toolchain being used, particularly with newer Python releases like 3.12+ where `libcst` might not have prebuilt wheels.
fix
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.
AttributeError: 'CSTNode' object has no attribute 'code_for_node'
The `code_for_node` method is available on a `Module` object, not directly on individual `CSTNode` instances, as it requires the module's context (like indentation and newline formats) to correctly render code.
fix
Access `code_for_node` through the `Module` object from which the node was parsed: `module.code_for_node(your_cst_node)`.
Upgrade
Version history
1.9.0latest on PyPI · released Jul 29, 2026
Audit
Dependencies
Rust toolchainrequiredRequired for building from source if pre-built binary wheels are not available for your system. Binary wheels are provided for Linux/Windows x86/x64 and Mac x64/arm.
Agent activity
10 hits · last 30 days
node
8
Amazon
1
Resources
libcst — pip install libcst · libregistry