Another form of dynamic import

Albert Hopkins marduk at letterboxes.org
Wed Mar 25 15:14:07 EDT 2009


Also, instead of caching exceptions you can do lazy lookups kinda like
this:

-------------------------------------------------------------------------------------
# a.py

class A:
    pass

-------------------------------------------------------------------------------------
# b.py

class B:
    pass

-------------------------------------------------------------------------------------
# c.py

class D:
    pass

class E:
    pass

-------------------------------------------------------------------------------------
# iface.py

class LazyInterface(object):
    _attr_dict = dict(A='a', B='b', C='c', D='c')
    _attr_cache = dict()
    _mod_cache = dict()

    def __getattr__(self, name):
        if name in self._attr_cache:
            return self._attr_cache[name]

        elif name in self._attr_dict:
            module_name = self._attr_dict[name]
            self._mod_cache[module_name] = 
		self._mod_cache.get(module_name,__import__(module_name))
            self._attr_cache[name] =
 		getattr(self._mod_cache[module_name], name)
            return self._attr_cache[name]
        else: raise AttributeError


>>> from iface import LazyInterface
>>> i = LazyInterface()
>>> a = i.A()
>>> a
<a.A instance at 0x7fb034317440>
>>> c = i.C()
>>> c
<c.C instance at 0x7fb034317758>
>>> d = i.D()
>>> d
<c.D instance at 0x7fb0343177a0>

There is probably a cleaner/more robust way of doing the above, but you
get the idea.




More information about the Python-list mailing list