How is the Python grammar used internally?

后端 未结 4 1545
难免孤独
难免孤独 2020-12-09 16:59

I\'m trying to get a deeper understanding of how Python works, and I\'ve been looking at the grammar shown at http://docs.python.org/3.3/reference/grammar.html.

I no

4条回答
  •  感动是毒
    2020-12-09 17:31

    The python grammar - as most others - is given in BNF or Backus–Naur Form. Try reading up on how to read it but the basic structure is:

     ::= ( | [some fixed things]) [...]
    

    This is read as a is defined as something else or any of the fixed things repeated a multitude of times.

    BNF is based on a nearly 2000 year old format for describing the permitted structure of a language, is incredibly terse and will describe all the allowed structures in a given language, not necessarily all those that would make sense.

    Example

    Basic arithmetic can be described as:

     ::= [ ]...([ ]...|)
     ::= [][...][.[...]]
     ::= +|-
     ::= [+-*/]
     ::= [0123456789]
    

    Which says that a simple arithmetic operation is an, optionally signed, number consisting of one or more digits, possibly with a decimal point and one, or more, subsequent digits, optionally followed by spaces, followed by exactly one of +-*/, optionally followed by spaces, followed by either a number or another simple arithmetic operation, i.e. a number followed by, etc.

    This describes, just about, all of the basic arithmetic operations and can be extended to include functions, etc. Notice that does allow invalid operations that are a valid syntax, e.g.: 22.34 / -0.0 is valid syntactically even though the result is not valid.

    It can sometimes make you aware that operations are possible that you might not have thought of, e.g.: 56+-50 is a valid operation as is 2*-10 but 2*/3 is not.

    Note that SGML and XML/Schema are both related but different methodologies for describing the structure of any language. YAML is another method for describing the allowed structures in a computer specific languages.

    Disclaimer: My BNF is a little rusty so if I have made any major mistakes in the above my apologies and please correct me.

提交回复
热议问题