diff options
author | Sylvain <syt@logilab.fr> | 2007-12-21 14:50:30 +0100 |
---|---|---|
committer | Sylvain <syt@logilab.fr> | 2007-12-21 14:50:30 +0100 |
commit | 3f91a94d6404d472eee1357db65421374bc5dc60 (patch) | |
tree | b29bb27adf591b30ab45d15f3936ccc9ee9c01f0 | |
parent | e0a4afb5ab565005790714f18aa3e559aebb5b25 (diff) | |
download | logilab-common-3f91a94d6404d472eee1357db65421374bc5dc60.tar.gz |
new LazyObject class
-rw-r--r-- | ChangeLog | 3 | ||||
-rw-r--r-- | modutils.py | 25 |
2 files changed, 25 insertions, 3 deletions
@@ -3,7 +3,8 @@ ChangeLog for logilab.common -- * db: binarywrap support - + * modutils: new LazyObject class + 2007-12-20 -- 0.25.2 * adbh: new needs_from_clause variable on db helper diff --git a/modutils.py b/modutils.py index 221d5d6..4ceb83b 100644 --- a/modutils.py +++ b/modutils.py @@ -1,5 +1,5 @@ # -*- coding: iso-8859-1 -*- -# Copyright (c) 2003-2006 LOGILAB S.A. (Paris, FRANCE). +# Copyright (c) 2003-2008 LOGILAB S.A. (Paris, FRANCE). # http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This program is free software; you can redistribute it and/or modify it under @@ -17,7 +17,7 @@ """Python modules manipulation utility functions. :author: Logilab -:copyright: 2003-2006 LOGILAB S.A. (Paris, FRANCE) +:copyright: 2003-2008 LOGILAB S.A. (Paris, FRANCE) :contact: http://www.logilab.fr/ -- mailto:python-projects@logilab.org @@ -59,6 +59,27 @@ class NoSourceFile(Exception): source file for a precompiled file """ +class LazyObject(object): + def __init__(self, module, obj): + self.module = module + self.obj = obj + self._imported = None + + def __getobj(self): + if self._imported is None: + self._imported = getattr(load_module_from_name(self.module), + self.obj) + return self._imported + + def __getattribute__(self, attr): + try: + return super(LazyObject, self).__getattribute__(attr) + except AttributeError, ex: + return getattr(self.__getobj(), attr) + + def __call__(self, *args, **kwargs): + return self.__getobj()(*args, **kwargs) + def load_module_from_name(dotted_name, path=None, use_sys=1): """load a Python module from it's name |