1
請查看以下代碼片段。屬性在運行時未知,但在pdb調試期間已識別
我在if語句中得到一個UnboundLocalError: "local variable 'os' referenced before assignment"
錯誤。
我在那裏設置了一個pdb跟蹤,我試圖檢查os模塊。
import os
import pdb
...
pdb.set_trace()
if not os.path.exists(path_to_temp):
os.makedirs(path_to_temp)
這是我在PDB離奇的互動:
(Pdb) os.path.exists(path_to_temp)
False
(Pdb) not os.path.exists(path_to_temp)
True
(Pdb) os.path
<module 'posixpath' from '/usr/lib/python2.7/posixpath.pyc'>
(Pdb) os
<module 'os' from '/usr/lib/python2.7/os.pyc'>
(Pdb) n
UnboundLocalError: "local variable 'os' referenced before assignment"
我甚至不...
編輯:媽呀,可恥的是我。我在當地的import os
這個if語句之後有一個地方!
嘗試在'if'之前添加'print os'。看看是否觸發了相同的行爲。 – Marcin
天哪,看我的編輯.. – Diana
這是有道理的python變量範圍規則,雖然它在某種意義上是一個角落的情況。 – Marcin