Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Railroad diagram for Python grammar

Tags:

python

I am looking for a way to get better grasp on the Python grammar. My experience is that a railroad diagram for the grammar may be helpful.

Python documentation contains the grammar in a text form:

https://docs.python.org/3/reference/grammar.html

But that is not very easy to digest for someone who is just starting with software engineering.

Anybody has a good beginners material?

There is a Railroad Diagram Generator that I might be able to use, but I was not able to find an EBNF syntax for the Python grammar, that would be accepted by that generator. A link to such a grammar would be very helpful as well.

like image 242
Ilya Bobyr Avatar asked Apr 08 '15 20:04

Ilya Bobyr


1 Answers

To convert the Python grammar found at, e.g., https://docs.python.org/3/reference/grammar.html, to EBNF, you basically need to do three things:

  1. Replace all #... comments with /*...*/ (or just delete them)
  2. Use ::= instead of : for defining production rules
  3. Use (...)? to indicate optional elements instead of [...].

For example, instead of

# The function statement
funcdef: 'def' NAME parameters ['->' test] ':' suite

you would use

/* The function statement */
funcdef ::= 'def' NAME parameters ('->' test)? ':' suite
like image 84
chepner Avatar answered Oct 05 '22 07:10

chepner