copy.deepcopy raises TypeError on objects with self-defined __new__() method

一笑奈何 提交于 2019-12-01 16:05:37
mata

one problem is that deepcopy and copy have no way of knowing which arguments to pass to __new__, therefore they only work with classes that don't require constructor arguments.

the reason why you can have __init__ arguments is that __init__ isn't called when copying an object, but __new__ must be called to create the new object.

so if you want to control copying, you'll have to define the special __copy__ and __deepcopy__ methods:

def __copy__(self):
    return self

def __deepcopy__(self, memo):
    return self

by the way, singletons are evil and not really needed in python.

Seems to me you want the Symbol instances to be singletons. Deepcopy, however is supposed to be used when you want an exact copy of an instance, i.e. a different instance that is equal to the original.

So the usage here kinda contradicts the purpose of deepcopy. If you want to make it work anyhow, you can define the __deepcopy__ method on Symbol.

Define __getnewargs__ — that way you will not only be able to copy and deepcopy, but you'll also be able to pickle.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!