Created
December 2, 2008 04:06
-
-
Save clofresh/30986 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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