In the 6th IPC, there was a paper "Design Patterns in Python", wherein a decent singleton pattern is presented. There are some other patterns such as CoR, Proxy. http://www.python.org/workshops/1997-10/proceedings/savikko.html June Kim "Chris Green" <cmg at uab.edu> wrote in message news:m2ae5glo95.fsf at phosphorus.tucc.uab.edu... > I'm revisiting python after several years away and implementing a > medium sized project with it. One of the first things I'm doing is > trying to get a few helper util functions working > > After doing some websearches for OO Singleton implementations, I came > across http://www-md.fsl.noaa.gov/eft/developer/python/hints/ftul.html > which has Fredrik Lundh's code. > > How would one improve upon this? I'm still not fully in the python > mindset and I'd like to brainwash myself somemore before I get deep > into the project and realize I wanted better basics. > > There's some testing code as well so it should be fairly > self-explanatory. > > # Registry Singleton Ideas taken from Fredrik Lundh <Fredrik_Lundh at ivab.se> > # > # A Python Pattern: "Singleton/F" > > class _SingletonRegistry: > instance = None > registry = {} > > def __init__(self): > pass > > def getClass(self, Class, *args, **keywords): > print "ARGS = " + str(args) > print "class: " + str(Class) > print "keywords: " + str(keywords) > > try: > f = self.registry[Class] > except KeyError: > self.registry[Class] = apply(Class, args, keywords) > > print "CLASS: " + str(self.registry[Class]) > return self.registry[Class] > > > def SingletonRegistry(): > """ Returns a SingletonRegistry reference, creating it if necessary """ > if not _SingletonRegistry.instance: > _SingletonRegistry.instance = _SingletonRegistry() > > return _SingletonRegistry.instance > > > if __name__ == '__main__': > class Foo: > name = 'wee' > > class Bar: > def __init__(self, *args): > print "Bar.__init__ args: " + str(args) > > class Baz: > def __init__(self, *args, **keywords): > print "Bar.__init__ args: " + str(args) > print "Baz.__init__ keywords: " + str(keywords) > > > sr = SingletonRegistry() > > myFoo = sr.getClass(Foo) > myFoo2 = sr.getClass(Foo) > > myBar = sr.getClass(Bar, "arg1", "arg2") > myBar2 = sr.getClass(Bar, "arg1", "arg2") > > myBaz = sr.getClass(Baz, "arg1", "arg2", cheese=1, beer=2) > myBaz2= sr.getClass(Baz, "arg1", "arg2", cheese=1, beer=2) > > print "myFoo :" + str(myFoo) > print "myFoo2 :" + str(myFoo2) > print "myBar :" + str(myBar) > print "myBar2 :" + str(myBar2) > print "myBaz :" + str(myBaz) > print "myBaz2 :" + str(myBaz2) > > -- > Chris Green <cmg at uab.edu> > You now have 14 minutes to reach minimum safe distance.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4