Search code examples
python-3.xebnf

EBNF for a function in python


Am new to python and would like to know how to write an ebnf for a function. I made the following-

id ⇐ definition of legal function/variable name
val ⇐ definition of legal int value

use
def, comma, parentheses, and colon

This is what I did, but I don't think its correct:

def id([id=val,id=val]):

Solution

  • Language Reference -> Compound statements -> Function definitions has this:

    funcdef        ::=  [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite
    decorators     ::=  decorator+
    decorator      ::=  "@" dotted_name ["(" [parameter_list [","]] ")"] NEWLINE
    dotted_name    ::=  identifier ("." identifier)*
    parameter_list ::=  (defparameter ",")*
                        | "*" [parameter] ("," defparameter)* ["," "**" parameter]
                        | "**" parameter
                        | defparameter [","] )
    parameter      ::=  identifier [":" expression]
    defparameter   ::=  parameter ["=" expression]
    funcname       ::=  identifier
    

    The grammar in the doc is not always the same as the one used to generate the parser. (The latter may be less readable.) And even the parser grammar may be incomplete as some constraints are only enforced when compiling. The one above does not quite capture the constraint that once a default value is given, all subsequent positional parameters must have a default. The production for parameter list seems like it may have other problems.

    Simplifying by removing decorators, annotations, and all "*' stuff, but adding the constraint, using mostly your style, and ignoring the issue of a final, trailing comma being optional, results in

    def id '(' (id,)* (id=val,)* ')' :

    (The literal ()s must be quoted to differentiate them from the grouping ()s.)