草庐IT

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

coder 2023-08-21 原文

所以我明白了:

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词法分析——逻辑行&复合语句的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  4. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  5. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  6. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  7. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  8. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  9. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  10. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

随机推荐