2013-05-14 88 views
6

我在Python 3.3.1(win7)中有一個奇怪的NameError。Python:NameError:在封閉範圍內賦值之前引用的自由變量're'

的代碼:

import re 

# ... 

# Parse exclude patterns. 
excluded_regexps = set(re.compile(regexp) for regexp in options.exclude_pattern) 

# This is line 561: 
excluded_regexps |= set(re.compile(regexp, re.I) for regexp in options.exclude_pattern_ci) 

錯誤:

Traceback (most recent call last): 
    File "py3createtorrent.py", line 794, in <module> 
    sys.exit(main(sys.argv)) 
    File "py3createtorrent.py", line 561, in main 
    excluded_regexps |= set(re.compile(regexp, re.I) for regexp in options.exclude_pattern_ci) 
    File "py3createtorrent.py", line 561, in <genexpr> 
    excluded_regexps |= set(re.compile(regexp, re.I) for regexp in options.exclude_pattern_ci) 
NameError: free variable 're' referenced before assignment in enclosing scope 

注意,行561,其中發生了錯誤,是在上面的代碼中的線。換句話說:re而不是一個自由變量。它只是正則表達式模塊,它可以在第一行行中被完美地引用。

在我看來,提到re.I是造成這個問題,但我不知道如何。

+0

如果您從行561中刪除're.I',錯誤消失嗎?我懷疑它 - 這個問題很可能是由於你在問題中遺漏了某些東西造成的。 – alexis 2013-05-14 14:06:56

+0

嘗試提供一個http://sscce.org/。 – glglgl 2013-05-14 14:11:33

+0

@alexis你是對的。如果我刪除're.I',錯誤不會消失。 – robert 2013-05-14 14:14:52

回答

5

最有可能的是,您正在re(大概是無意)指定下面的第561行,但功能相同。這再現了您的錯誤:

import re 

def main(): 
    term = re.compile("foo") 
    re = 0 

main() 
+0

你說得對。我再次在該行下面的某個位置導入了re模塊(本地到函數範圍)。然而,我沒有得到的是爲什麼Python沒有抱怨第一行然後... – robert 2013-05-14 14:22:39

+0

很高興它的工作。如果你可以構造一個能夠再現你的問題的最小例子,我們可以爲你解釋python的語義。現在你真的沒有提供足夠的信息。 – alexis 2013-05-14 14:25:03

+0

下面是一個重現錯誤的腳本:http://pastebin.com/yQN89y4A Python在第13行拋出NameError(與第12行相反)。 – robert 2013-05-14 14:27:59

6

「自由變量」中的回溯表明,這是在封閉範圍的局部變量。是這樣的:

baz = 5 

def foo(): 
    def bar(): 
     return baz + 1 

    if False: 
      baz = 4 

    return bar() 

使得baz指的是一個局部變量(一個誰值爲4),而不是(想必也是存在的)全球性的。爲了解決這個問題,迫使baz到全球:

def foo(): 
    def bar(): 
     global baz 
     return baz + 1 

,以便它不會嘗試名稱解析爲巴茲非本地版本。更好的是,以一種看起來像局部變量(生成器表達式/列表解析是一個檢查的好地方)的方式找到你正在使用re的地方,並將其命名爲別的東西。

相關問題