pythonparsingcpython

Parsing a source code with just one digit


Could some please walk me through, how CPython parses a file contain just one character 1?

In particular, why ast.parse("3") returns ...Expr(...)... as (I believe) Python's source code is a list of statements?

In other words, reading the grammar how do I go from file to ... atom (I guess)?


Solution

  • An expression can also be a statement, the rule sequence is:

    file -> statements -> statement -> 
        simple_stmts -> simple_stmt -> star_expressions -> star_expression -> 
        expression
    

    After all, func(x) is also an expression, and a file print('Hello world!') is perfectly valid.