Search code examples
pythonbuttonkivydeep-copy

Python deepcopy changes the reference to an object


Hi: This is a follow up to this question:

How to copy all python instances to a new class?

The problem is that deepcopy() is not copying the objects correctly, this can be seen through this working code:

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout

class MyApp(App):
    def build(self):
        global Myroot    
        self.root = FloatLayout()
        Myroot = self.root
        Starthere(None)

        return

class VarStorage:
    pass

VS=VarStorage()
from kivy.uix.button import Button
import copy

def Starthere(instance):
    VS.MyButton=Button()
    print str(VS.MyButton)
    VSCopy=copy.deepcopy(VS)
    print str(VSCopy.MyButton)

MyApp().run()

From my understanding of copy, it should print twice the same button, but the result is:

<kivy.uix.button.Button object at 0x046C2CE0>
<kivy.uix.button.Button object at 0x04745500>

How to make deepcopy() copy the same object instead of a new (non existing) one? Thank you!

---------------------- EDIT -----------------------------

After trying copy() instead of deepcopy(), its not what Im intending to do:

What I get with deepcopy():

  • Copied class of VS, with copied items for those which are not objects (for instance, if VS.text="text", VSCopy.text will have the same contents without being linked whatsoever).
  • But, for objects, what I need is a copy of the reference to such object, which I dont get, since I get a new reference pointint a new object.

What I get with copy():

  • Copied class VSCopy with refferences pointing to original class VS. I dont want this since I want to change VS's contents (thats why Im trying to copy it) and still have the original ones available in VSCopy.

Is there such a function in copy module?


Solution

  • Is there such a function in copy module?

    No, I'm afraid there is not.

    It sounds like you want some sort of hybrid deep/shallow behavior, and that's not what exists in the copy module. You either get a shallow copy, or a deep one.

    Sorry for the bad news. :) You may just want to write your own copier, or see if you can accomplish your task without copying per se.

    (I see you edited your question, so I've answered again to see if I can help. (Please see my first answer for a response to your original Q.))