Removing modules from the global namespace

David Bolen db3l at fitlinxx.com
Tue May 15 15:02:23 EDT 2001


Chris Jaeger <cjaeger at ensim.com> writes:

> 	I have a python program that I want to import
> a number of modules into, but I don't know what the
> set of modules are going to be until run-time. Each
> loadable module exports an identical API. My layout
> currently is:

Here's something I just did recently for something similar, although I
insert lazy module definitions (borrowed from DateTime) into a
dictionary for use by the calling module rather than it depending on
dir().  It also skips any files in the directory beginning with "_"
(which covers __init__ and some internal-package only modules I have):

    #
    # -------------------------------------------------------------------
    #

    def find_modules():
	import sys, os, fnmatch, string
	import DateTime.LazyModule

	LazyModule = sys.modules['DateTime.LazyModule']

	# Walk the current directory to identify all management modules,
	# and store a reference to them within the returned dictionary.

	modfiles = filter(lambda x,m=fnmatch.fnmatch:m(x,'*.py'),
			  os.listdir(__path__[0]))

	modules    = {}

	for curmodule in modfiles:
	    modname = os.path.splitext(curmodule)[0]
	    if modname[0] == '_':
		continue
	    else:
		modules[modname] = LazyModule.LazyModule(__name__+'.'+modname,
							 locals(),globals())

	return modules

    #
    # -------------------------------------------------------------------
    #

    modules = find_modules()

    del find_modules


Assuming a package directory (call it "nimgmt") of:

  nimgmt/
    Demo.py
    Disk.py
    Inventory.py
    System.py
    _DBAccess.py
    _RegAccess.py
    __init__.py

then you get the following:

    >>> import nimgmt
    >>> dir(nimgmt)
    ['__builtins__', '__doc__', '__file__', '__name__', '__path__', 'modules']
    >>> pprint.pprint(nimgmt.modules)
    {'Demo': <lazy module 'nimgmt.Demo'>,
     'Disk': <lazy module 'nimgmt.Disk'>,
     'Inventory': <lazy module 'nimgmt.Inventory'>,
     'System': <lazy module 'nimgmt.System'>}
    >>> 

and thus the calling application can iterate over the supported
modules, and then access them through the dictionary value.  Doing the
access will actually import the module (which will create a module
entry in the global space of the package).

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list