python线程无法识别变量,在赋值之前引用的局部变量'image'

时间:2016-12-09 14:51:45

标签: python multithreading

for image in self._images:
            if image.ID == _id:
                if image.deletable:
                    # TODO: if deletable remove it also from Docker

                    def image_delete_thread():
                        image.destroy()
                        self._images.remove(image)
                        del image # this should in the end also delete the image if possible

                    thread.start_new_thread(image_delete_thread, ())

                    return make_response(jsonify({'success': 'Image >' + _id + '< deleting.'}), 202)
                return make_response(jsonify({'success': 'Image >' + _id + '< not deletable.'}), 400)
        return make_response(jsonify({'error': 'Container image: >' + _id + '< not found!'}), 404)

我收到以下错误:执行线程时。为什么新线程无法识别变量图像?

分配前引用的

局部变量'image'

2 个答案:

答案 0 :(得分:1)

由于

而失败
del image

线。 del运算符没有按照您的想法执行操作。看看这个:

>>> import dis
>>> def test():
...     x = 1
...     del x
... 
>>> dis.dis(test)
  2           0 LOAD_CONST               1 (1)
              3 STORE_FAST               0 (x)

  3           6 DELETE_FAST              0 (x)
              9 LOAD_CONST               0 (None)
             12 RETURN_VALUE

现在你可以read in docs

  

DELETE_FAST(var_num)

     

删除本地co_varnames [var_num]。

换句话说,del运算符用于变量(不要将其与del x[idx]运算符区分开)从本地删除变量。由于image_delete_thread与调用者共享其范围,因此您获得ReferenceError的原因。简单的例子:

>>> def test():
...     x = 1
...     del x
...     x += 1
...
>>> test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in test
UnboundLocalError: local variable 'x' referenced before assignment

删除del image行,就可以了。无论如何都没有必要。

答案 1 :(得分:0)

nonlocal image添加到image_delete_thread的第一行。如果您使用的是Python 2.X,PEP 3104中提出了一些建议的解决方法,它提出了nonlocal的定义