Skip to main content

A library for regex-inspired fine-grained AST pattern matching and replacing

Project description

AST Pattern Engine

A powerful, programmatic, regex-inspired AST pattern matching and manipulation library for Python.

Philosophy: The "Gradual Pipeline"

Instead of relying on fragile regex on source code or magic string-to-AST parsers, ast_pattern_engine provides an internal DSL for building explicit, structural patterns.

It is designed with a "Gradual Pipeline" philosophy: instead of writing one massive, monolithic pattern expression to do everything at once, you chain small, focused patterns and visitors. Like casting a wide net and progressively filtering down in stages.

Installation

pip install ast_pattern_engine
uv add ast_pattern_engine

(Requires Python 3.10+)

Quick Start

Here is a simple pipeline that rewrites dict.get("key") calls into direct subscript access dict["key"]:

from typing import Any
import ast
from ast_pattern_engine import BottomUpPatternTransformer, Bind, NodePattern

source = "value = my_dict.get(other_dict.get('foo'))"
tree = ast.parse(source)

# 1. Build the explicit structural pattern
# Matches: <obj>.get(<key>)
pattern = [
    NodePattern(
        ast.Call,
        func=NodePattern(ast.Attribute, attr="get", value=Bind("obj")),
        args=Bind("key"),
    )
]

# 2. Define the rewrite logic
def rewrite_dict_get(bindings: dict[str, Any]) -> list[ast.AST]:
    obj = bindings["obj"]
    key = bindings["key"][0]  # args is a list

    # Return the new node to replace the matched node
    new_node = ast.Subscript(value=obj, slice=key, ctx=ast.Load())
    return [new_node]

# 3. Apply the transformer
# We use BottomUpPatternTransformer so nested `.get()` calls
# are safely transformed from the inside-out.
transformer = BottomUpPatternTransformer(pattern, {"key": rewrite_dict_get})
transformer.visit(tree)

print(ast.unparse(tree))
# Output: value = my_dict[other_dict['foo']]

(See the examples/ directory for full runnable code).

Primitives

The engine provides several primitives to build robust sequences:

  • NodePattern: Match specific AST node types and assert on their fields.
  • Collect / Bind: Extract sub-trees out of a matched pattern to use in your handlers.
  • OneOf: Match one of several possible patterns (similar to regex |).
  • Repetition: Match a pattern sequentially 1 or more times (similar to regex * and +).
  • Optional: Match a pattern 0 or 1 times (similar to regex ?).
  • Filter: Apply arbitrary Python lambdas to check node states during matching.

Templates

To reduce boilerplate when building patterns, the library includes a templates module with helpers for common operations:

  • match_call(func_name, **kwargs)
  • match_assign(target_name, value)
  • match_in_expr(pattern)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ast_pattern_engine-1.0.1.tar.gz (20.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ast_pattern_engine-1.0.1-py3-none-any.whl (15.1 kB view details)

Uploaded Python 3

File details

Details for the file ast_pattern_engine-1.0.1.tar.gz.

File metadata

  • Download URL: ast_pattern_engine-1.0.1.tar.gz
  • Upload date:
  • Size: 20.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.2

File hashes

Hashes for ast_pattern_engine-1.0.1.tar.gz
Algorithm Hash digest
SHA256 0005c7a022d401053b341dd9cf53544a4fc81e17442ba614292b40145cbc5dd6
MD5 10bbfbfb395b3eeb0035181dace92621
BLAKE2b-256 6c53aee57c4a70e86fef06110bb8950132d273b122d173b44ecdcce7e1419db3

See more details on using hashes here.

File details

Details for the file ast_pattern_engine-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for ast_pattern_engine-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 439ec869b1d65dcffe3a8a7853827dc73c9d41b5109d6f327cbbfe251715deb8
MD5 d6bf25fb9b4bffe48e97d5d7dc68ca85
BLAKE2b-256 58bdeacdf83fe84ded67da4d7b37e4ecb2b5a94805405cd1c583a469e1d127d3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page