1

enter image description here

Hey.

So I got this "data" class that contains a dictionary with functions that modify it's contents. And I have 2 widgets that I want to update whenever the data is changed. The data can be changed from "widget1" or from an outside call (somewhere else)

But whenever it's changed (red arrows), i need to call the widgets to update and display the new data (blue arrows).

So I tried to make this "data" class a singleton:

    def __new__(cls):
        if not hasattr(cls, "instance"):
            cls.instance = super(MyDataClass, cls).__new__(cls)
        print(cls.instance)
        return cls.instance

(which does seem to work as the print statement returns the same address twice)
<MyDataClass object at 0x00000243882A25E0>
<MyDataClass object at 0x00000243882A25E0>

and then each widget can add it's separate callback in a list:

    def addCallbackFunction(self, f):
        self.callbacks.append(f)

    def _callCallbackFunctions(self):
        for f in self.callbacks:
            f()

But when I make the second instance, the list of callbacks (self.callbacks) is empty. And only showing the 2nd callback.

EDIT: To clarify what I'm doing in the widgets:

class Widget1():

    def __init__():
        self.data = MyDataClass()
        self.data.addCallbackFunction(self.callback1)

    def callback1():
        print("x")


class Widget2():

    def __init__():
        self.data = MyDataClass()
        self.data.addCallbackFunction(self.callback2)

    def callback2():
        print("y")

My expectation is that self.callbacks from "data" class contains callback1 and callback2... but it seems to only contain callback2 twice...

<bound method callback2 object at 0x000001AC8E98D970>>
<bound method callback2 object at 0x000001AC8E98D970>>

What am i missing? Or is there a better way of doing this whole thing? :)

Thanks.

Andrei M.
  • 313
  • 2
  • 10

1 Answers1

0

The answer was here: https://stackoverflow.com/a/6255101/9525238

The problem was that my list of callbacks was inside the init and not defined in the class itself, so it was recreated after each instance.

before:

class MyDataClass:
    def __init__(self):
        self.callbacks = []

after:

class MyDataClass:
    callbacks = []
    def __init__(self):
        pass
Andrei M.
  • 313
  • 2
  • 10