Skip to main content

Chain-structured data and pattern matching with .xxx.yyy syntax

Project description

latychain

Immutable chain-structured data with backtracking pattern matching.

from latychain import Chain, ChainPatternAtom

# Chain([…]) — standard explicit construction
rule = Chain([ChainPatternAtom.any(0), "uuu", ChainPatternAtom.rex(r"x\d")])
data = Chain(["x", "uuu", "x1"])
data.match(rule)   # True

Two shortcuts: import ChainPatternAtom as Patom, and build with / instead of []:

from latychain import Chain, ChainPatternAtom as Patom

rule = Chain / Patom.any(0) / "uuu" / Patom.rex(r"x\d")
data = Chain / "x" / "uuu" / "x1"
data.match(rule)   # True

Plus compile-time .xxx.yyy sugar for opted-in modules:

# useLatyChain
data = .heading.h1
rule = .any(0).uuu.rex(r"x\d")
data.match(rule)   # True

Install

pip install latychain

Python 3.10+.


Core concepts

Chain — immutable ordered container

Elements are plain strings (data) or ChainPatternAtom instances (pattern rules). Hashable, usable as dict keys.

c = Chain(["a", "b", "c"])
len(c)              # 3
c[0]                # 'a'
str(c)              # '.a.b.c'
c.to_list()         # ['a', 'b', 'c']
"b" in c            # True

# Matching (backtracking, non-greedy)
c.match(Chain(["a", "b"]))               # False — full match fails
c.match(Chain(["a", "b"]), partial=True) # True — prefix match
c.startswith(Chain(["a", "b"]))          # True — same as partial

# pathlib-style / shortcut
Chain / "a" / "b" / "c"                  # same as Chain(["a","b","c"])

ChainPatternAtom — pattern atoms

Factory Matches
any(min=1, max=0) N arbitrary elements (max=0 = unbounded). Non-greedy.
rex(pattern) Single element via regex fullmatch
enum(*chains) One of several alternative chains
apply(func, long=1) Custom predicate receiving a Chain of long elements
long(min, max=None) String length in [min, max]
un(value) Any element not equal to value
ext(chain=None) Optional segment — match or skip

Import as ChainPatternAtom (full name) or Patom (shortcut):

from latychain import Chain, ChainPatternAtom
# or
from latychain import Chain, ChainPatternAtom as Patom
# any — between min and max arbitrary elements
rule = Chain([ChainPatternAtom.any(0), "yyy"])  # 0 or more before 'yyy'
Chain(["x", "yyy"]).match(rule)                 # True
Chain(["yyy"]).match(rule)                      # True

# rex — regex fullmatch on one element
Chain(["h1"]).match(Chain([ChainPatternAtom.rex(r"h[12]")]))    # True
Chain(["123"]).match(Chain([ChainPatternAtom.rex(r"\d+")]))     # True

# enum — pick one alternative
rule = Chain([ChainPatternAtom.enum(
    Chain(["user", ChainPatternAtom.any(0)]),
    Chain(["admin", ChainPatternAtom.any(0)]),
)])
Chain(["user", "login"]).match(rule)   # True
Chain(["guest"]).match(rule)           # False

# ext — optional segment
rule = Chain(["a", ChainPatternAtom.ext(Chain(["pi"])), "b"])
Chain(["a", "b"]).match(rule)      # True — ext skipped
Chain(["a", "pi", "b"]).match(rule) # True — ext matched
Chain(["a", "x", "b"]).match(rule)  # False

# apply — custom predicate
rule = Chain([ChainPatternAtom.apply(lambda c: str(c).startswith(".x"))])
Chain(["xhello"]).match(rule)   # True

# long — string length constraint
Chain(["abc"]).match(Chain([ChainPatternAtom.long(3)]))        # True
Chain(["abc"]).match(Chain([ChainPatternAtom.long(2, 5)]))     # True

# un — negation
Chain(["user"]).match(Chain([ChainPatternAtom.un("admin")]))   # True

.xxx.yyy syntax sugar

An import hook transforms .xxx.yyy expressions into Chain([...]) calls at compile time. Opt-in per module — add # useLatyChain to the first few lines. Chain and ChainPatternAtom are auto-injected, no explicit import needed.

Requires two files — the hook only transforms imported modules, not the entry script:

runner.py (no sugar):

import latychain.ChainDotRule   # registers the hook
import my_code                   # this file gets transformed

my_code.py (uses sugar):

# useLatyChain

# Segments without () → strings; with () → ChainPatternAtom.xxx()
data = .heading.h1                       # → Chain(['heading', 'h1'])
rule = .any(0).uuu.rex(r'x\d')

x = .x.uuu.x1
x.match(rule)                             # True

# Nested enum
rule2 = .any(0).enum(
    .admin.any(0),
    .user.any(0),
).rex(r'\d+')

Chain(["user", "login", "123"]).match(rule2)   # True

The transformer skips strings, comments, float literals, and obj.attr access. Only files with # useLatyChain are transformed — all other imports pass through untouched.

Numeric segments (.123) are not supported — use Chain(["123"]) instead.


Develop

git clone https://github.com/fnsii/latychain
cd latychain
uv venv && source .venv/bin/activate   # Windows: .venv\Scripts\activate
uv run python test/run_all.py

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

latychain-0.2.0.tar.gz (26.9 kB view details)

Uploaded Source

Built Distribution

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

latychain-0.2.0-py3-none-any.whl (18.7 kB view details)

Uploaded Python 3

File details

Details for the file latychain-0.2.0.tar.gz.

File metadata

  • Download URL: latychain-0.2.0.tar.gz
  • Upload date:
  • Size: 26.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for latychain-0.2.0.tar.gz
Algorithm Hash digest
SHA256 a6a2682b7e49e3461080db938d1144ae4b8463d7ac755246bbc778a9029733bf
MD5 77d6adad89a7d904e7157abeeed8e1b6
BLAKE2b-256 631e2c694884fd920688b89fa9dca4c4b67719055f7814a3560a12bb9baf92dd

See more details on using hashes here.

Provenance

The following attestation bundles were made for latychain-0.2.0.tar.gz:

Publisher: publish.yml on fnsii/latychain

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file latychain-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: latychain-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 18.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for latychain-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e81c9b961d29182d59126c26689880991eefe7e5721acbe39ea426101c11c9a2
MD5 e350fdc237e7fd651d8f35366d898de0
BLAKE2b-256 272032880c7dcc6c52eba5ea169df7a0723a94ae3c896a220d4f84723f0c7be3

See more details on using hashes here.

Provenance

The following attestation bundles were made for latychain-0.2.0-py3-none-any.whl:

Publisher: publish.yml on fnsii/latychain

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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