[Zope] Copying Objects of a Python Class

Thomas Guettler zopestoller@thomas-guettler.de
Thu, 25 Apr 2002 17:21:26 +0200


I solved it. I use the following lines for copying an object:

orig # the original (instance of MyClass())
copy=MyClass()
copy.__setstate__(orig.__getstate__())

  thomas

Thomas Guettler wrote:

> Hi!
> 
> If I copy an instance of a python class (I am developing a python product)
> I got the problem that it does a deep copy. The original
> has a attribute called default_catalog which is
> a reference to the catalog where all objects are stored.
> 
> If I do a copy, there is a unfortunately
> a new object (default_catalog). But it should be a reference
> to the catalog where all objects are stored.
> 
> I store a template in the folder 'defaults' and want
> to copy it to 'documents'. (Layout: root/defaults root/documents)
> 
> In the Object which gets copied:
>   def createNewDocument(self, REQUEST=None):
>         r=self.root()
>         orig=r.defaults[self.id]
>         copy=orig._getCopy(r)
> 
>         # Stolen form CopySupport.manage_clone. Don't know what it does
>         copy=copy.__of__(orig)
> 
>         copy.id=r.nextID()
>         copy.isDefaultDocument=0
>         r.documents._setObject(copy.id, copy) # TODO: Btree
>         if copy.default_catalog!=orig.default_catalog:
>             print "orig", orig.default_catalog
>             print "copy", copy.default_catalog
>             raise "Bad Copy"
>         if REQUEST:
>             REQUEST.RESPONSE.redirect('/' + r.id + '/documents/' + copy.id)
> 
> The log:
> orig <ZCatalog instance at 02633AB8>
> copy <ZCatalog instance at 02522EC0>
> --> there is a new object
> 
> _getCopy does this (From Zope's CopySupport.py):
>     def _getCopy(self, container):
>         # Ask an object for a new copy of itself.
>         f=tempfile.TemporaryFile()
>         self._p_jar.exportFile(self._p_oid,f)
>         f.seek(0)
>         ob=container._p_jar.importFile(f)
>         f.close()
>         return ob
> 
> I think the export and reimport creates new objects.
> 
> I think I will write my own copy method and don't use _getCopy except
> someone has a solution
> 
> Thank you for listening.
> 
>  thomas