简体   繁体   English

缩进的缺乏是否可以保证Python的顶级上下文?

[英]Does a lack of indentation guarantee a top-level context in Python?

I'm working on a script parser that expands embedded Python code into script code by extracting all Python code into a single file so that it can remember Python variables defined earlier in the script. 我正在研究一个脚本解析器,该脚本解析器通过将所有Python代码提取到一个文件中来将嵌入式Python代码扩展为脚本代码,以便它可以记住脚本中先前定义的Python变量。 In order to substitute the Python output in the appropriate places in the script, it therefore cares about both Python's output, and the line number that produced this output. 为了在脚本的适当位置替换Python输出,因此,它既关心Python的输出,又关心产生此输出的行号。 So I would like to generate Python code like this: 所以我想生成这样的Python代码:

sys.stdout = ... # Write function reads _lineNumber and includes it in the output
_lineNumber = 1 # this line automatically inserted
print("qwerty") # from line 1
_lineNumber = 2 # this line automatically inserted
def foobar(x):
    print(x)
_lineNumber = 4
if True:
    foobar("fdsa") # from line 4
_lineNumber = 6
foobar("asdf") # from line 6

Note however that I have to skip lines 3 and 5 because they are not at the top-level context--changing _lineNumber during the function call would be incorrect behavior, and changing _lineNumber during the if would require matching the indentation and is unnecessarily complicated when I can simply require that the user complete all code blocks such as functions and conditionals in the same block of script code. 但是请注意,我必须跳过第3行和第5行,因为它们不在顶级上下文中-在函数调用期间更改_lineNumber会是错误的行为,而在if期间更改_lineNumber则需要匹配缩进,并且在执行时会不必要地复杂我可以简单地要求用户在同一脚本代码块中完成所有代码块,例如函数和条件。 My problem is ensuring that it is always valid to perform the assignment to _lineNumber when I do--the lines between the assignments are arbitrary code. 我的问题是确保在执行_lineNumber分配时始终有效-分配之间的行是任意代码。 My question is, if the following line has no indentation, does that guarantee that it is syntactically valid to insert an assignment to _lineNumber on the previous line, or is there any other python grammar that would make the scheme of inserting an assignment before every unindented line be invalid? 我的问题是,如果以下行没有缩进,是否可以保证在前一行上向_lineNumber插入赋值在语法上是有效的,或者是否存在任何其他python语法可以使在每个未缩进之前插入赋值的方案行无效吗?

No; 没有; while indentation at the start of the line can tell you the the depth of context of that statement, it is still possible for many things such as lists to cause one line to span multiple code lines, and other statements such as else can be connected to earlier statements despite having no indentation. 虽然行首的缩进可以告诉您该语句的上下文深度,但是诸如列表之类的许多事情仍然有可能导致一行跨越多个代码行,而其他语句(例如else可以连接到尽管没有缩进,但早期的声明。 There's no simple way to do this; 没有简单的方法可以做到这一点。 short of getting into the python parsing, you'd have to rely on the user to return to the top level context at well-defined points. 除了需要进行python解析外,您还必须依靠用户在定义明确的位置返回顶层上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM