classification
Title: deepcopy of weakref proxies
Type: behavior Stage:
Components: Library (Lib) Versions: Python 3.9
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: konrad.schwarz
Priority: normal Keywords:

Created on 2021-02-18 12:19 by konrad.schwarz, last changed 2021-02-18 12:19 by konrad.schwarz.

Messages (1)
msg387226 - (view) Author: Konrad Schwarz (konrad.schwarz) Date: 2021-02-18 12:19
copy.deepcopy()-ing a tree structure that has internal parent and cross-reference links implemented as weakref.proxy() objects causes the weak reference proxies themselves to be copied (still refering to their original referents) rather than weak references to deep-copied referents to be created.

A workaround is to add the following __deepcopy__ method to affected classes:
    def __deepcopy__ (self, memo):
        # taken from Stackoverflow: "How to override the
        # copy deepcopy operations for a python object"
        # and "Python: dereferencing weakproxy"
        cls = self.__class__
        result = cls.__new__ (cls)
        memo [id (self)] = result
        for k, v in self.__dict__.items ():
            if isinstance (v, weakref.ProxyType):
                new_v = weakref.proxy (copy.deepcopy (
                        v.__repr__.__self__, memo))
            else:
                new_v = copy.deepcopy (v, memo)
            setattr (result, k, new_v)
        return result
History
Date User Action Args
2021-02-18 12:19:01konrad.schwarzcreate