[Python-Dev] Autoloading? (Making Queue.Queue easier to use)

Greg Ewing greg.ewing at canterbury.ac.nz
Thu Oct 13 07:25:58 CEST 2005

I wrote:

> I'll see if I can cook up an example of it to show. Be
> warned, it is very hackish...

Well, here it is. It's even slightly uglier than I thought
it would be due to the inability to change the class of a
module these days.

When you run it, you should get

Imported my_module
Loading the spam module
Glorious processed meat product!
Glorious processed meat product!


#  test.py

import my_module

print "Imported my_module"


#  my_module.py

import autoloading
autoloading.register(__name__, {'spam': 'spam_module'})

#  spam_module.py

print "Loading the spam module"

def spam():
   print "Glorious processed meat product!"

#  autoloading.py

import sys

class AutoloadingModule(object):

   def __getattr__(self, name):
     modname = self.__dict__['_autoload'][name]
     module = __import__(modname, self.__dict__, {}, [name])
     value = getattr(module, name)
     setattr(self, name, value)
     return value

def register(module_name, mapping):
   module = sys.modules[module_name]
   m2 = AutoloadingModule()
   m2.__name__ = module.__name__
   m2.__dict__ = module.__dict__
   # Drop all references to the original module before assigning
   # the _autoload attribute. Otherwise, when the original module
   # gets cleared, _autoload is set to None.
   sys.modules[module_name] = m2
   del module
   m2._autoload = mapping


Greg Ewing, Computer Science Dept, +--------------------------------------+
University of Canterbury,	   | A citizen of NewZealandCorp, a	  |
Christchurch, New Zealand	   | wholly-owned subsidiary of USA Inc.  |
greg.ewing at canterbury.ac.nz	   +--------------------------------------+

More information about the Python-Dev mailing list