Skip to main content

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

Project description

PyPI - Version PyPI - Python Version Pytest MIT License Codecov GitHub Workflow Status

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.2.tar.gz (23.1 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.2-py3-none-any.whl (15.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: ast_pattern_engine-1.0.2.tar.gz
  • Upload date:
  • Size: 23.1 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.2.tar.gz
Algorithm Hash digest
SHA256 b37d77cbe44883a3692e6ffe8aab16674525d8b591ff6dc532ee04bf228c98cf
MD5 6af969eff72ad3e238ce5bfcc968079f
BLAKE2b-256 f69cb87634f4619f933b7cfd6758b50582176153a02214c3ab2b4e55338aff91

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for ast_pattern_engine-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 f4bf6ceda274e4b9f375050991f17a639e295e0326b195ff2fa1a420c03fb204
MD5 9188053a7e19a51c9ff19e38602027d2
BLAKE2b-256 ed3759e040678c3f43a64dc504bd60a3c06f3e3035958fa9cd94bc98ad4116d8

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