python + twisted + gtk:KeyboardInterrupt导致自由变量?

时间:2010-08-26 12:53:19

标签: python variables gtk scope twisted

我正在使用GTK扭曲,并且在无法建立连接时运行以下代码:

def connectionFailed(self, reason):
    #show a "connect failed" dialog
    dlg = gtk.MessageDialog(
        type=gtk.MESSAGE_ERROR,
        buttons=gtk.BUTTONS_CLOSE,
        message_format="Could not connect to server:\n%s" % (
            reason.getErrorMessage()))
    responseDF = defer.Deferred()
    dlg.set_title("Connection Error")
    def response(dialog, rid):
        dlg.hide_all()
        responseDF.callback(rid)
    dlg.connect("response", response)
    dlg.show_all()

    self.shutdownDeferreds.append(responseDF)

self.shutdownDeferreds是设置的延迟列表,以便反应堆在被调用之前不会停止。

现在,我碰巧在连接失败的同时按CTRL+C。弹出对话框,但是当我按Close时,我得到:

Traceback (most recent call last):
  File "C:\Users\DrClaud\bumhunter\gui\controller.py", line 82, in response
    dlg.hide_all()
NameError: free variable 'dlg' referenced before assignment in enclosing scope
Traceback (most recent call last):
  File "C:\Users\DrClaud\bumhunter\gui\controller.py", line 82, in response
    dlg.hide_all()
NameError: free variable 'dlg' referenced before assignment in enclosing scope

为什么会发生这种情况的任何想法?

1 个答案:

答案 0 :(得分:1)

不应该是:

def response(dialog, rid):
    dialog.hide_all()
    responseDF.callback(rid)

或者真的,为了清楚起见,

def response(self, rid):
    self.hide_all()
    responseDF.callback(rid)

(我可能错了,我几乎没有做任何GTK。)如果是这样,问题是你在函数中引用dlg,这使它成为一个闭包(它捕获{{1来自其周围的范围)。 dlg将导致奇怪和奇妙的行为,因为它可能会破坏该范围。