On Wed, 2007-03-07 at 19:06 +1100, Edward d'Auvergne wrote:
Hi, After careful thought about design patterns, I've decided to try to use the singleton pattern for the old 'self.relax.data' data structure. See http://en.wikipedia.org/wiki/Singleton_pattern for more information about this design pattern. I'll try to use the second simple example under the heading 'Python Borg pattern'. The benefit of this pattern is that each module can use the code: from data import Data relax_data = Data() As Data will be a singleton if two modules used by relax instantiate the Data class then the global 'relax_data' in both modules will be the same instance. Therefore if a method from the 'special_fns.model_free' module modifies the data structure, all the other relax modules using the singleton will see the changes. The benefit of this pattern is that the data structure is similar in concept to a global variable but only modules utilising it will have it in one of their namespaces. Also 'self.relax.data' will not need to be passed around inside the program, simplifying the code. What do you think of the idea?
One issue here, identified on the wikipedia page, is that __init__() is called for each call of Singleton(). Therefore all of the standard __init__() stuff - inialising variables and empty containers - will happen every time the Singleton instance is sought. This is clearly not what we want. Ofcourse there are many ways around that by cleverly hiding the initialisation stuff, but its starting to look like a complex solution to what should be a simple problem. Something like: class Data: ... Data = Data() in the data module, then everywhere else: from data import Data as relax_data By rebinding the name 'Data' with an instance of the class, we effectively prevent accidental creation of additional instances, and the import makes that instance availible wherever we need it. Chris
Cheers, Edward P.S. Another idea would be to create the variable 'relax_data.current_run'. The 'relax_data' singleton structure will be a dictionary type as proposed in the redesign discussions, hence you would have say 'relax_data['m5']' being another object containing all the model-free model m5 data, but the variable could be part of the singleton data structure. The data object of the current run could then be accessed as 'data = relax_data[relax_data.current_run]'. This is probably an anti-pattern so please feel free to suggest better ideas.