PyPEG2

raw JSON →
2.15.2 verified Fri May 01 auth: no python

An intrinsic PEG Parser-Interpreter for Python, providing a simple way to define grammars using Python classes. Current version 2.15.2; no regular release cadence.

pip install pypeg2
error AttributeError: module 'pypeg2' has no attribute 'parse'
cause Incorrect import; installed `pypeg` instead of `pypeg2`.
fix
Install correct package: pip install pypeg2 and use from pypeg2 import parse.
error TypeError: 'Symbol' object does not support indexing
cause Treating a parsed `Symbol` as a tuple/list instead of accessing its attributes.
fix
Parse result is an object with attributes; use dot notation like result.name.first.
error ImportError: cannot import name 'Parser' from 'pypeg2'
cause Typo in import; correct symbol is `Parser` but some older documentation shows `parser` (lowercase).
fix
Use correct import: from pypeg2 import Parser (capital P).
gotcha PyPEG2 uses Python's `str` as a base class for `Symbol`, which means that parsed values become strings. Be careful with type checks and comparisons.
fix Use the parsed object's attributes directly; do not rely on type identity.
deprecated The `pypeg2` library is not actively maintained and may have compatibility issues with newer Python versions (e.g., Python 3.10+).
fix Consider using alternative PEG parser generators like `parsimonious` or `lark-parser` for new projects.
gotcha Grammar definitions using tuples and `attr` can be confusing. Order of elements in tuple matters for parsing sequence.
fix Always use `attr` to define fields; the order of tuple elements defines the parse order.

Define a simple grammar with classes and parse a string.

from pypeg2 import Symbol, Keyword, attr, parse

class Name(Symbol):
    grammar = attr('first', str), attr('last', str)

class Greeting(Keyword):
    grammar = 'hello'

class Sentence:
    grammar = Greeting, Name

result = parse('hello John Doe', Sentence)
print(result.greeting, result.name.first, result.name.last)