#!/usr/bin/env python """ dynimp.py - Import Modules On First Use Author: Sean B. Palmer, inamidst.com Example use: import dynimp dynimp.dynimp('sys') print sys.version """ import inspect class DynamicModule(object): """DynamicModule(name, frame) -> new dynamic module.""" cache = {} def __init__(self, name, frame): DynamicModule.cache[self] = (name, frame) def __repr__(self): name, frame = DynamicModule.cache[self] return "" % (name, id(self)) def __import(self): name, frame = DynamicModule.cache[self] module = __import__(name) dynmod = 'global %s\n%s = module' % (name, name) exec(dynmod, frame.f_globals, locals()) return module def __setattr__(self, attr, obj): module = self.__import() setattr(module, attr, obj) def __getattr__(self, attr): module = self.__import() return getattr(module, attr) def dynimp(*names): frame = inspect.currentframe() for name in names: yield DynamicModule(name, frame) def test(): global sys, os print "Dynamically importing" sys, os = dynimp('sys', 'os') print "Testing dynamically imported modules" print sys, '.'.join(str(n) for n in sys.version_info) print sys, sys.version print os.path.isdir('/') if __name__=="__main__": test()