Python grammar for tree-sitter

0.25.0 · active · verified Thu Apr 09

tree-sitter-python (version 0.25.0) provides a pre-compiled Python grammar for the tree-sitter parsing library. It enables Python applications to efficiently parse Python source code into concrete syntax trees, facilitating tasks like static analysis, code transformation, and IDE features. The library is actively maintained with regular updates following the upstream tree-sitter project.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load the Python grammar and parse a simple Python code snippet. It initializes a `Language` object using `tree_sitter_python.language()`, creates a `Parser`, and then parses a byte string of Python code into a syntax tree. The root node's type and its first child's type are printed.

from tree_sitter import Language, Parser
import tree_sitter_python

# Initialize the Python language grammar
PY_LANGUAGE = Language(tree_sitter_python.language())

# Create a parser and configure it to use the Python language
parser = Parser(PY_LANGUAGE)

# Source code to parse
code = b"""
def greet(name):
    print(f"Hello, {name}!")

greet("World")
"""

# Parse the code
tree = parser.parse(code)

# Get the root node of the syntax tree
root_node = tree.root_node

# Print the type of the root node and its first child (for demonstration)
print(f"Root node type: {root_node.type}")
if root_node.children:
    print(f"First child type: {root_node.children[0].type}")

# Expected output might vary slightly but should show 'module' and 'function_definition'

view raw JSON →