I am creating an Observer in a Python 3 app to be shared across modules, so I'm trying to combine both Observer and Singleton patterns. Using the Borg approach specified in "Software Architecture with Python" and elsewhere, I came up with the following:
class Borg(object):
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
class Publisher(Borg):
def __init__(self):
Borg.__init__(self)
self.subscribers = {}
Now I can use a "subscribe" function on Publisher to add subscribers. Any new subscribers are added to self.subscribers and the code works fine.
The problem is the line self.subscribers = {}
. I have created a race condition, so if a module using this observer starts a bit later, that line erases all current subscribers. If I was using discrete values, like p.x = 5
(where p = Publisher()
) then this wouldn't have been an issue.
Any suggestions on how I can preserve the subscribers list across multiple Publisher instantiations? I did put subscribers in Borg itself and that seems to work, but I'm wondering if a more Pythonic way exists. I can get rid of __dict__ altogether if all I am doing is keeping the shared state in Borg.
Aucun commentaire:
Enregistrer un commentaire