Parsley

1.3 · abandoned · verified Sun Apr 12

Parsley is a Python parsing library designed to simplify parsing and pattern matching. It implements the Parsing Expression Grammar (PEG) algorithm, compiling grammar definitions into Python classes where rules become methods. This approach aims to make parsing expressions behave similarly to standard Python expressions. It is an implementation of OMeta, an object-oriented pattern-matching language. The current version is 1.3, released in 2017.

Warnings

Install

Imports

Quickstart

This quickstart defines a simple grammar for basic arithmetic (addition, multiplication, and integers). It demonstrates how to create a grammar, instantiate a parser with input, and execute a rule to get the result. Note the use of `-> int(ds)` to convert matched digit strings to integers and `-> left + right` for performing calculations within the grammar itself.

import parsley

grammar_source = """
    integer = <digit+>:ds -> int(ds)
    sum = integer:left '+' integer:right -> left + right
    product = integer:left '*' integer:right -> left * right
    expression = sum | product | integer
"""

calculator_grammar = parsley.makeGrammar(grammar_source, {})

# Parse a sum
parser_sum = calculator_grammar("10+20")
result_sum = parser_sum.sum()
print(f"10+20 = {result_sum}") # Expected: 30

# Parse a product
parser_product = calculator_grammar("5*6")
result_product = parser_product.product()
print(f"5*6 = {result_product}") # Expected: 30

# Parse a single integer
parser_int = calculator_grammar("123")
result_int = parser_int.integer()
print(f"123 = {result_int}") # Expected: 123

view raw JSON →