在this question中,Anthony Hatchkins提供了基于dict复制代码的深度复制的默认实现,Python可以追溯到:
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
setattr(result, k, deepcopy(v, memo))
return result
我想要一个基于pickling和unpickling的默认实现,Python在选择dict-copy之前会选择。
这是我的尝试,但没有效果:
def __deepcopy__(self, memo):
new, args, state = self.__reduce__()
result = new(*args)
if state:
result.__setstate__(state)
memo[id(self)] = result
return result
一旦我有了这样的方法,我就可以创建一个版本,其中包含有关复制内容和复制方式的其他选项。
reduce和setstate的存在由定义的基类保证:
@staticmethod
def kwargs_new(cls, new_kwargs, *new_args):
"""
Override this method to use a different new.
"""
retval = cls.__new__(cls, *new_args, **new_kwargs)
retval.__init__(*new_args, **new_kwargs)
return retval
"""
Define default getstate and setstate for use in coöperative inheritance.
"""
def __getstate__(self):
return {}
def __setstate__(self, state):
self.__dict__.update(state)
def __getnewargs_ex__(self):
return ((), {})
def __reduce__(self):
"""
Reimplement __reduce__ so that it calls __getnewargs_ex__
regardless of the Python version.
It will pass the keyword arguments to object.__new__.
It also exposes a kwargs_new static method that can be overridden for
use by __reduce__.
"""
new_args, new_kwargs = self.__getnewargs_ex__()
state = self.__getstate__()
return (type(self).kwargs_new,
(type(self), new_kwargs,) + tuple(new_args),
state)
答案 0 :(得分:0)
传递给setstate的状态需要像参数列表那样被复制:
def __deepcopy__(self, memo):
"""
Reimplement __deepcopy__ so that
* it supports keyword arguments to reduce.
"""
kwargs = memo.get('deepcopy kwargs', {})
new, args, state = self.__reduce__(**kwargs)
args_copy = copy.deepcopy(args, memo)
result = new(*args_copy)
memo[id(self)] = result
if state:
state_copy = copy.deepcopy(state, memo)
result.__setstate__(state_copy)
return result
此版本的deepcopy已被修改为使用特殊备忘录将关键字参数传递给reduce。
答案 1 :(得分:0)
另一种选择是通过减少检查堆栈帧来传递关键字参数以减少:
def f():
import inspect
for frame_tuple in inspect.stack():
if 'x' in frame_tuple[0].f_locals:
x = frame_tuple[0].f_locals['x']
print(x)
def g():
x = 5
f()
g()