Python 词法分析 - 逻辑行 & 复合语句

Python lexical analysis - logical line & compound statements

所以我明白了:

The end of a logical line is represented by the token NEWLINE

这意味着 Python 语法的定义方式是结束逻辑行的唯一方法是使用 \n 标记。

物理线也是如此(而不是 EOL,这是您在编写文件时使用的平台的 EOL,但仍然被 Python 转换为通用 \n

一条逻辑线可以等同于也可以不等同于一条或多条物理线,但通常是一条,如果您编写干净的代码,大多数情况下就是一条。

在某种意义上:

foo = 'some_value'  # 1 logical line = 1 physical  
foo, bar, baz = 'their', 'corresponding', 'values'  # 1 logical line = 1 physical
some_var, another_var = 10, 10; print(some_var, another_var); some_fn_call()

# the above is still still 1 logical line = 1 physical line
# because ; is not a terminator per se but a delimiter
# since Python doesn't use EBNF exactly but rather a modified form of BNF

# p.s one should never write code as the last line, it's just for educational purposes

没有显示 1 个逻辑如何等同于 > 1 个物理的示例,我的问题是来自文档的以下部分

Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax (e.g., between statements in compound statements)

但这到底是什么意思?我了解复合语句的列表,它们是:if、while、for、 等。它们都是由一个或多个 子句 组成的每个 子句 依次由 a headera 组 组成。 suite由一个或多个statements组成,举个例子更具体一点:

所以if语句根据语法是这样的(不包括elifs和else子句):

if_stmt ::=  "if" expression ":" suite

其中套件及其后续语句:

suite         ::=  stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement     ::=  stmt_list NEWLINE | compound_stmt
stmt_list     ::=  simple_stmt (";" simple_stmt)* [";"]

所以这意味着如果您愿意,您可以选择(由“|”给出)您的套房是以下两种方式之一:

  1. 同一行:

    缺点:不是pythonic,你不能有另一个引入新块的复合语句(如func def,另一个if等)

    优点:我猜是一个班轮

示例:

if 'truthy_string': foo, bar, baz = 1, 2, 3; print('whatever'); call_some_fn();
  1. 引入新区块:

    优点:全部,以及正确的做法

示例:

if 'truthy_value':
    first_stmt = 5
    second_stmt = 10
    a, b, c = 1, 2, 3
    func_call()
    result = inception(nested(calls(one_param), another_param), yet_another))

但我不明白

Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax

我在上面看到的是一个套件,它是由if 子句代码块控制的代码块 =82=],反过来,suite,是由逻辑的、独立的行(语句)组成的,其中每个逻辑行都是一个物理行(巧合)。我看不出一条逻辑线如何跨越边界(这基本上只是结束、极限、换行符的花哨词),我看不出一个语句如何跨越这些边界并跨越到下一个声明,或者也许我真的很困惑,把所有东西都搞混了,但如果有人能解释一下。

提前感谢您抽出时间。

Python语法

幸运的是 Python 文档中有一个 Full Grammar specification

该规范中的语句定义为:

stmt: simple_stmt | compound_stmt

逻辑线由 NEWLINE 分隔(这不在规范中,但基于您的问题)。

Step-by-step

好的,让我们来看看这个

的规格是什么

simple_stmt:

simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
             import_stmt | global_stmt | nonlocal_stmt | assert_stmt)

好吧,现在它进入了几个不同的路径,单独通过所有路径可能没有意义,但根据规范 simple_stmt 可以跨越逻辑线边界 if 任何 small_stmt 包含 NEWLINE(目前它们 可以).

除了理论上的可能性之外,实际上

compound_stmt:

compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated | async_stmt
[...]
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
[...]
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT

我只选择了 if 语句和 suite 因为它已经足够了。 if语句包括elifelse以及其中的所有内容为一个语句(复合语句)。并且因为它可能包含 NEWLINEs(如果 suite 不仅仅是一个 simple_stmt)它已经满足 "a statement that crosses logical line boundaries".

的要求

一个例子if(原理图):

if 1:
    100
    200

将是:

if_stmt
|---> test        --> 1
|---> NEWLINE
|---> INDENT
|---> expr_stmt   --> 100
|---> NEWLINE
|---> expr_stmt   --> 200
|---> NEWLINE
|---> DEDENT

所有这些都属于 if 语句(它不仅仅是 ifwhile 的块 "controlled",...)。

parser, symbol and token

相同的if

一种可视化方法是使用 built-in parsertokensymbol 模块(真的,我之前不知道这个模块写下答案):

import symbol
import parser
import token

s = """
if 1:
    100
    200
"""
st = parser.suite(s)

def recursive_print(inp, level=0):
    for idx, item in enumerate(inp):
        if isinstance(item, int):
            print('.'*level, symbol.sym_name.get(item, token.tok_name.get(item, item)), sep="")
        elif isinstance(item, list):
            recursive_print(item, level+1)
        else:
            print('.'*level, repr(item), sep="")

recursive_print(st.tolist())

实际上我无法解释大部分 parser 结果,但它表明(如果你删除了很多不必要的行) suite 包括它的换行符确实属于 if_stmt .缩进表示解析器在特定点的"depth"。

file_input
.stmt
..compound_stmt
...if_stmt
....NAME
....'if'
....test
.........expr
...................NUMBER
...................'1'
....COLON
....suite
.....NEWLINE
.....INDENT
.....stmt
...............expr
.........................NUMBER
.........................'100'
.......NEWLINE
.....stmt
...............expr
.........................NUMBER
.........................'200'
.......NEWLINE
.....DEDENT
.NEWLINE
.ENDMARKER

这可能会变得更漂亮,但我希望即使是目前的形式也能作为插图。

它比你想象的要简单。复合语句被视为单个语句,即使它内部可能有其他语句。引用 docs:

Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line.

例如,

if a < b:
    do_thing()
    do_other_thing()

是一个单独的 if 语句,占用 3 个逻辑行。这就是语句可以跨越逻辑行边界的方式。