具有修饰功能的多处理池使我“对象没有属性”

时间:2019-11-28 23:31:38

标签: python python-multiprocessing

下面是可复制的代码:

from multiprocessing import Pool

def method_exception_catcher(method):

    def method_exception_caught(*args, **kwargs):

        try:
            return method(*args, **kwargs)

        except Exception as e:
            raise type(e)(str(e) + ' from [{}] method'.format(method.__name__)) 

    return method_exception_caught

class MyClass():

    @method_exception_catcher
    def do_something(self, elem):
        return 1/0

    @method_exception_catcher
    def parallel_do_something(self):

        with contextlib.closing(Pool(processes=1)) as p:

            procs = [p.apply_async(self.do_something, args=(3, )) for k in range(1)]
            results = [proc.get() for proc in procs]
            p.close()
            p.join()

        return results

MyClass().parallel_do_something()

该代码给我“ AttributeError:'MyClass'对象没有属性'method_exception_caught'”错误。

如何解决此问题并成功将其除以0错误?谢谢!

更新:

这是完整的错误输出:

Process ForkPoolWorker-4:
Traceback (most recent call last):
  File "/usr/lib64/python3.6/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib64/python3.6/multiprocessing/process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/lib64/python3.6/multiprocessing/pool.py", line 108, in worker
    task = get()
  File "/usr/lib64/python3.6/multiprocessing/queues.py", line 337, in get
    return _ForkingPickler.loads(res)
AttributeError: 'MyClass' object has no attribute 'method_exception_caught'

1 个答案:

答案 0 :(得分:0)

选择一个函数只会写下其(模块和)名称;解开(导入模块并)查找名称。由于您的类的方法(即装饰器返回的函数)的__name__method_exception_caught,因此就是酸洗所使用的。

答案(出于其他原因也是个好主意)是使用functools.wraps来使包装函数模拟包装的函数:

def decorator(f):
  @functools.wraps(f)
  def wrap(*a,**kw): return f(*a,**kw)
  return wrap