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

标签 python python-3.x python-internals bnf

所以我明白了:

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、 等。它们都是由一个或多个子句和每个子句组成的,又由一个标题一个套件组成。 suite由一个或多个语句组成,我们举个例子更具体一点:

所以 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,你不能有另一个引入新 block 的复合语句(比如func def、另一个if等)

    优点:我猜是一条线

例子:

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

    优点:所有,以及正确的方法

例子:

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

提前感谢您抽出时间。

最佳答案

Python语法

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

该规范中的声明定义为:

stmt: simple_stmt | compound_stmt

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

循序渐进

好吧,让我们来看看这个,a 的规范是什么

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 可以 交叉逻辑行边界如果任何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 这里面的所有内容都是一个语句(复合语句)。并且因为它可能包含 NEWLINE(如果 suite 不仅仅是一个 simple_stmt),它已经满足了“一个跨越的语句”的要求逻辑线边界”。

if 示例(示意图):

if 1:
    100
    200

会是:

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

所有这些都属于 if 语句(并且它不仅仅是一个由 ifwhile 来“控制”的 block ,...)。

parser 相同的if , symboltoken

一种可视化方法是使用内置的 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。缩进表示解析器在特定点的“深度”。

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

这可能会变得更漂亮,但我希望即使是目前的形式也能起到说明作用。

关于Python词法分析——逻辑行&复合语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49529410/

相关文章:

python - workalendar.europe 图书馆 : how to find holidays

python - `groupby` 的实现特定行为和参数解包

Python SQLAlchemy 检查非类型

python - 根据行条件对轴 1 上的数据框进行子集化

python - Pandas - 不同字符串之间的比较始终返回 True

python - Cpython VM 是否为每个操作码执行 C 代码?

python - 元组在 CPython 中是如何实现的?

python - 如何将python中的数据导出为ex​​cel格式?

Python使用存储在变量中的将stdout和stderr发送到多个文件

python-3.x - Tensorboard 投影仪可视化 - PCA 不断加载