Skip to content

Instantly share code, notes, and snippets.

@clofresh
Created December 2, 2008 04:06
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 clofresh/30986 to your computer and use it in GitHub Desktop.
Save clofresh/30986 to your computer and use it in GitHub Desktop.
class Lazy(type):
def __init__(cls, name, bases, dict):
super(Lazy, cls).__init__(name, bases, dict)
cls.instance = None
def check_instance(cls):
if cls.instance is None:
if hasattr(cls, 'instantiate'):
setattr(cls, 'instance', getattr(cls, 'instantiate')())
else:
raise Exception('Must implement the instantiate class method!')
def __getattr__(cls, name):
cls.check_instance()
return getattr(cls.instance, name)
def __getitem__(cls, key):
cls.check_instance()
return cls.instance.__getitem__(name)
def __iter__(cls):
cls.check_instance()
return cls.__iter__()
def __contains__(self, item):
cls.check_instance()
return cls.__contains__(item)
class db(object):
__metaclass__ = Lazy
@classmethod
def instantiate(cls):
return db_connection()
def func1():
db.execute('SELECT * FROM things')
def func2():
db.execute('SELECT * FROM other_things')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment