1# Python Tree Sitter {#python-tree-sitter} 2 3[Tree Sitter](https://tree-sitter.github.io/tree-sitter/) is a framework for building grammars for programming languages. It generates and uses syntax trees from source files, which are useful for code analysis, tooling, and syntax highlighting. 4 5Python bindings for Tree Sitter grammars are provided through the [py-tree-sitter](https://github.com/tree-sitter/py-tree-sitter) module. The Nix package `python3Packages.tree-sitter-grammars` provides pre-built grammars for various languages. 6 7For example, to experiment with the Rust grammar, you can create a shell environment with the following configuration: 8 9```nix 10{ 11 pkgs ? import <nixpkgs> { }, 12}: 13 14pkgs.mkShell { 15 name = "py-tree-sitter-dev-shell"; 16 17 buildInputs = with pkgs; [ 18 (python3.withPackages ( 19 ps: with ps; [ 20 tree-sitter 21 tree-sitter-grammars.tree-sitter-rust 22 ] 23 )) 24 ]; 25} 26``` 27 28Once inside the shell, the following Python code demonstrates how to parse a Rust code snippet: 29 30```python 31# Import the Tree Sitter library and Rust grammar 32import tree_sitter 33import tree_sitter_rust 34 35# Load the Rust grammar and initialize the parser 36rust = tree_sitter.Language(tree_sitter_rust.language()) 37parser = tree_sitter.Parser(rust) 38 39# Parse a Rust snippet 40tree = parser.parse( 41 bytes( 42 """ 43 fn main() { 44 println!("Hello, world!"); 45 } 46 """, 47 "utf8" 48 ) 49) 50 51# Display the resulting syntax tree 52print(tree.root_node) 53``` 54 55The `tree_sitter_rust.language()` function references the Rust grammar loaded in the Nix shell. The resulting tree allows you to programmatically inspect the structure of the code. 56