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

后端 未结 3 1657
盖世英雄少女心
盖世英雄少女心 2021-01-17 20:42

I want to implement a symbol type, which keeps track of the symbols we already have(saved in _sym_table), and return them if they exist, or create new ones othe

相关标签:
3条回答
  • 2021-01-17 20:48

    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.

    0 讨论(0)
  • 2021-01-17 21:04

    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.

    0 讨论(0)
  • 2021-01-17 21:08

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

    0 讨论(0)
提交回复
热议问题