Python - 莳萝:不能泡菜装饰类

时间:2016-10-13 16:57:18

标签: python class decorator pickle dill

我有以下代码来装饰类:

import dill
from collections import namedtuple
from multiprocessing import Process

def proxified(to_be_proxied):
    b = namedtuple('d', [])

    class Proxy(to_be_proxied, b):
        pass

    Proxy.__name__ = to_be_proxied.__name__
    return Proxy


@proxified
class MyClass:
    def f(self):
        print('hello!')


pickled_cls = dill.dumps(MyClass)


def new_process(clazz):
    dill.loads(clazz)().f()


p = Process(target=new_process, args=(pickled_cls,))
p.start()
p.join()

当我试图挑选装饰类时,我收到以下错误:

Traceback (most recent call last):
  File "/usr/lib/python3.5/pickle.py", line 907, in save_global
    obj2, parent = _getattribute(module, name)
  File "/usr/lib/python3.5/pickle.py", line 265, in _getattribute
    .format(name, obj))
AttributeError: Can't get local attribute 'proxified.<locals>.Proxy' on <function proxified at 0x7fbf7de4b8c8>

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/carbolymer/example.py", line 108, in <module>
    pickled_cls = dill.dumps(MyClass)
  File "/usr/lib/python3.5/site-packages/dill/dill.py", line 243, in dumps
    dump(obj, file, protocol, byref, fmode, recurse)#, strictio)
  File "/usr/lib/python3.5/site-packages/dill/dill.py", line 236, in dump
    pik.dump(obj)
  File "/usr/lib/python3.5/pickle.py", line 408, in dump
    self.save(obj)
  File "/usr/lib/python3.5/pickle.py", line 475, in save
    f(self, obj) # Call unbound method with explicit self
  File "/usr/lib/python3.5/site-packages/dill/dill.py", line 1189, in save_type
    StockPickler.save_global(pickler, obj)
  File "/usr/lib/python3.5/pickle.py", line 911, in save_global
    (obj, module_name, name))
_pickle.PicklingError: Can't pickle <class '__main__.proxified.<locals>.Proxy'>: it's not found as __main__.proxified.<locals>.Proxy

如何使用莳萝腌制装饰类?我希望传递给这个类作为参数传递给一个单独的进程 - 也许有更简单的方法来做它?

1 个答案:

答案 0 :(得分:1)

GaëlVaroquauxcan be found here提供了一个很好的解释“为什么酸洗装饰功能很痛苦”。

基本上使用functools.wraps重写课程可以避免这些问题:)