Skip to content

Instantly share code, notes, and snippets.

@charlesreid1
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlesreid1/7d413ac914cee4ada47a to your computer and use it in GitHub Desktop.
Save charlesreid1/7d413ac914cee4ada47a to your computer and use it in GitHub Desktop.
Python Singleton Wrapper (Design Pattern)
class ExpensiveObjectToCreate(object):
'''Insert code here'''
pass
def __init__(self,**kwargs):
self.params = kwargs
def check(self):
print self.params
class SingletonWrapper(object):
"""
Wraps an expensive-to-create object that only needs to be initialized once.
"""
def __new__(self,**kwargs):
"""
Returns the expensive object, self.bling
"""
try:
return self.bling
except AttributeError:
self.bling = ExpensiveObjectToCreate(**kwargs)
return self.bling
if __name__=="__main__":
d = { 'a':1,
'b':2,
'c':'dog'}
print "Init data:"
print d
print "Creating an instance of the singleton wrapper..."
ps = SingletonWrapper(**d)
print "Done.\n"
print "Creating a second instance of the singleton wrapper..."
ps2 = SingletonWrapper()
print "Done.\n"
print "Here's the second instance's data:"
ps2.check()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment