Skip to content

Instantly share code, notes, and snippets.

@genbtc
Created March 3, 2025 19:30
Show Gist options
  • Save genbtc/7e6bc070d146b6d9a6eabfafc7618ca3 to your computer and use it in GitHub Desktop.
Save genbtc/7e6bc070d146b6d9a6eabfafc7618ca3 to your computer and use it in GitHub Desktop.
GPT-pyparsing-BNF.txt
You said:
Prompt:
for python is pyparsing library using BNF?
ChatGPT said:
Not exactly — Pyparsing doesn’t use Backus-Naur Form (BNF) directly, but it provides a more Pythonic, object-oriented approach to defining grammars.
BNF is a formal way to describe the syntax of languages, often used in compiler design and language parsing. Pyparsing, on the other hand, lets you build grammars by combining objects representing different parsing rules — like literals, keywords, expressions, and patterns — using Python’s operators and methods.
That said, you can implement a BNF-like grammar using Pyparsing, but you write it in a more procedural or declarative style, rather than using strict BNF notation. Pyparsing grammars tend to be easier to read and integrate with Python code compared to hand-written BNF.
Would you like me to show you an example of how you could express a BNF-style grammar in Pyparsing? Or maybe there’s a specific parsing task you’re thinking of?
You said:
yes, show the difference
ChatGPT said:
Alright, let’s take a simple example of an arithmetic expression and write it in both BNF and Pyparsing.
BNF for arithmetic expressions:
<expr> ::= <term> ( ("+" | "-") <term> )*
<term> ::= <factor> ( ("*" | "/") <factor> )*
<factor> ::= <number> | "(" <expr> ")"
<number> ::= [0-9]+
This describes the rules for parsing an arithmetic expression with addition, subtraction, multiplication, and division, including grouping with parentheses.
Now, the equivalent Pyparsing implementation:
from pyparsing import Word, nums, oneOf, Forward, Group, infixNotation, opAssoc
# Define number
number = Word(nums)
# Forward declaration for recursive expressions
expr = Forward()
# Operators
plus_minus = oneOf("+ -")
mult_div = oneOf("* /")
# Grouping terms and factors
factor = number | Group("(" + expr + ")")
term = factor + (mult_div + factor)[...]
expr <<= term + (plus_minus + term)[...]
# Parsing an example expression
example = "3 + 5 * (2 - 8)"
result = expr.parseString(example)
print(result)
Key differences:
BNF is purely a formal notation — it’s not executable directly. It’s more of a spec.
Pyparsing is an actual parser — you define parsing rules with Python objects and then use them directly.
In Pyparsing, we use constructs like Forward() for recursion and operators like +, |, and [...] to build parsing expressions.
Pyparsing grammar feels more like building a tree of objects than writing formal grammar notation, which makes it very flexible but also more readable in Python code.
Let me know if you want me to break down or tweak this example!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment