嵌套if语句中的python范围

时间:2017-04-27 09:41:52

标签: python if-statement scope

我正在编写一小段代码来解析latex文件,并为我提供了定义的新命令。测试用例就是这个简单的乳胶文件:

% +--------------------------------------------------------------------+
% |                                                                    |
% |  New particle stuff                                                |
% |                                                                    |
% +--------------------------------------------------------------------+
\newcommand*{\Hmp}{\ensuremath{H^{\mp}}\xspace}
\newcommand*{\susy}[1]{\ensuremath{\tilde{#1}}\xspace}
\newcommand*{\susy2}[1,2]{\ensuremath{\tilde{#1}\tilde{#2}}\xspace}

可能有一个更复杂的情况,命令扩展了几行,所以我需要跟踪不同的步骤,比如命令是否需要增加更多行,或者命令已经完成并准备好完成。< / p>

问题是,在几个嵌套的if / else语句中,变量的范围似乎丢失了,变量不再更新。这就是我在做什么:

    macros = []
    warg_keep = re.compile("newcommand\*\{(.*)\}\[(.*)\]\{(.*)")
    woarg_keep = re.compile("newcommand\*\{(.*)\}\{(.*)")
    warg_one = re.compile("newcommand\*\{(.*)\}\[(.*)\]\{(.*)\}")
    woarg_one = woarg = re.compile("newcommand\*\{(.*)\}\{(.*)\}") 
    keep = False
    for line in open(file).readlines():
        line = line.strip()
        if len(line) == 0 or line[0] == "%":
            continue
        if not keep:
            newcommand = {"key":"","command":"","args":[]}
        added = False
        if "newcommand" in line:
            if line[-1] == "%":
                clean_line = line[0:-1]
                keep = True
                newcommand = get_cmd_from_line(warg_keep,woarg_keep,clean_line)
            else:
                newcommand = get_cmd_from_line(warg_one, woarg_one, line)
                added = True
        elif keep:
            # Now it dos not matter how it ends, the command will always be added the line without the
            # last character, it can be either % or } but it shouldn't be added
            newcommand["command"] += line[0:-1]
            # End the keep
            if line[-1] != "%":
                keep = False
                added = True
        elif added:
            macros.append(newcommand)

问题是,当我为get_cmg_from_line函数分配newcommand变量时,我得到的值(我已经测试过的完美)它不会更新newcommand变量但是如果我将它移动到之前,那么它会识别它并更新它。保持和添加变量也会发生同样的事情。

我已经搜索了这个并且发现了很多关于范围/ if / functions等的事情我已经知道了,因为如果不能定义范围我就不知道为什么会发生这种情况......我错过了一些愚蠢的东西吗?我该如何更新newcommand变量的值?因为新的线路可能会更新。我看到的唯一解决方案是扁平化代码,但我想像这样维护它。

编辑:我改变了一些原始代码以适应文本的额外功能,但没有压扁代码,它也没有工作。因此,由于我提到的原因,顶部的代码不起作用。下面的代码完美地运行并通过所有测试:

macros = []
warg_keep = re.compile("newcommand\*\{(.*)\}\[(.*)\]\{(.*)")
woarg_keep = re.compile("newcommand\*\{(.*)\}\{(.*)")
warg_one = re.compile("newcommand\*\{(.*)\}\[(.*)\]\{(.*)\}")
woarg_one = woarg = re.compile("newcommand\*\{(.*)\}\{(.*)\}")
keep = False
for line in open(file).readlines():
    line = line.strip()
    if len(line) == 0 or line[0] == "%":
        continue
    if not keep:
        newcommand = {"key":"","command":"","args":[]}
    added = False
    if "newcommand" in line and line [-1] == "%":
        clean_line = line[0:-1]
        keep = True
        newcommand = get_cmd_from_line(warg_keep,woarg_keep,clean_line)
    if "newcommand" in line and line[-1] != "%":
        newcommand = get_cmd_from_line(warg_one, woarg_one, line)
        added = True
    if not "newcommand" in line and keep:
        # Now it dos not matter how it ends, the command will always be added the line without the
        # last character, it can be either % or } but it shouldn't be added
        newcommand["command"] += line[0:-1]            
    if not "newcommand" in line and keep and line[-1] != "%":
        # End the keep
        keep = False
        added = True
    if added:
        macros.append(newcommand)

2 个答案:

答案 0 :(得分:3)

粗略检查一下,我的第一个猜测是elif keepelif added应分别为if keepif added

另一种可能性是你期望newcommand从一行累积到下一行,但是你在每次传递时重置它。应该newcommand = { … }移动for line in …:吗?

答案 1 :(得分:0)

Python中的局部变量的范围(与许多其他脚本语言一样)是在功能级别,而不是在块级别。

示例:

def function():
    x = 5
    if True:
        y = 8
    print(x)
    print(y)

function()
# -> 5
# -> 8