FAQ
Hi all,

I was wondering if there was a way to remove
imported modules from a namespace. For instance, I
have an __init__.py that loads a dynamic list of modules
based on what it finds present in the directory. In order
to determine the contents of the directory, I need to import
os, string, etc. Before I return from __init__.py, I'd like
to remove all the modules from the namespace for this package
except for the ones that come from this directory. Can this
be done?

Here is my current __init__.py code:

import os
import re
import string

local_dir = os.path.dirname(__file__)
entries = os.listdir(local_dir)
for entry in entries:
if re.match(r"*.\.py$",entry) or re.match(r"*.\.pyc",entry):
module = string.join(string.split(entry,'.')[:-1],'.')
if module != "__init__":
__import__(module, globals(), locals(), [])

# this doesn't work
delattr(globals(), 'os')
delattr(globals(), 're')
delattr(globals(), 'string')

Search Discussions

  • Bjorn Pettersen at May 14, 2001 at 9:15 pm

    From: Chris Jaeger [mailto:cjaeger at ensim.com]

    Hi all,

    I was wondering if there was a way to remove
    imported modules from a namespace. For instance, I
    have an __init__.py that loads a dynamic list of modules
    based on what it finds present in the directory. In order
    to determine the contents of the directory, I need to import
    os, string, etc. Before I return from __init__.py, I'd like
    to remove all the modules from the namespace for this package
    except for the ones that come from this directory. Can this
    be done?
    Can't you just put your functionality in a function, and import the modules
    inside the function instead of at the global level?

    -- bjorn
  • Chris Jaeger at May 14, 2001 at 9:30 pm
    Hi Bjorn,

    Forgive me if this should be obvious; this is
    my first real exposure to python.

    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:

    main.py
    modules
    \_ __init__.py
    \_ module1.py
    \_ module2.py
    \_ ...
    \_ moduleN.py

    main.py imports modules, uses dir(modules)
    to get the list of names of imported modules, and then
    cycles though each module calling some function.
    Is there a better idiom to handle this than the one
    I am using? I would rather not modify modules/__init__.py
    every time a new module is placed in the modules directory.

    Thanks,
    Chris


    Bjorn Pettersen wrote:
    From: Chris Jaeger [mailto:cjaeger at ensim.com]

    Hi all,

    I was wondering if there was a way to remove
    imported modules from a namespace. For instance, I
    have an __init__.py that loads a dynamic list of modules
    based on what it finds present in the directory. In order
    to determine the contents of the directory, I need to import
    os, string, etc. Before I return from __init__.py, I'd like
    to remove all the modules from the namespace for this package
    except for the ones that come from this directory. Can this
    be done?
    Can't you just put your functionality in a function, and import the modules
    inside the function instead of at the global level?

    -- bjorn
  • David Bolen at May 15, 2001 at 7:02 pm

    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 \
    \-----------------------------------------------------------------------/
  • Bjorn Pettersen at May 14, 2001 at 9:53 pm

    From: Chris Jaeger [mailto:cjaeger at ensim.com]

    Hi Bjorn,

    Forgive me if this should be obvious; this is
    my first real exposure to python.

    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:

    main.py
    modules
    \_ __init__.py
    \_ module1.py
    \_ module2.py
    \_ ...
    \_ moduleN.py

    main.py imports modules, uses dir(modules)
    to get the list of names of imported modules, and then
    cycles though each module calling some function.
    Is there a better idiom to handle this than the one
    I am using? I would rather not modify modules/__init__.py
    every time a new module is placed in the modules directory.
    Sorry for not explaining well enough. I was thinking about something along
    these lines (__init__.py):

    def findModules():
    # these imports are local to this function
    import os
    import re
    import string
    res = []
    local_dir = os.path.dirname(__file__)
    entries = os.listdir(local_dir)
    for entry in entries:
    if re.match(r"*.\.py$",entry) or re.match(r"*.\.pyc",entry):
    module = string.join(string.split(entry,'.')[:-1],'.')
    if module != "__init__":
    res.append(module)
    return res

    for module in findModules():
    __import__(module, globals(), locals(), [])

    -- bjorn
  • Rainer Deyke at May 15, 2001 at 2:30 am
    "Chris Jaeger" <cjaeger at ensim.com> wrote in message
    news:mailman.989874501.32060.python-list at python.org...
    # this doesn't work
    delattr(globals(), 'os')
    delattr(globals(), 're')
    delattr(globals(), 'string')
    # This does:

    del os
    del re
    del string


    --
    Rainer Deyke (root at rainerdeyke.com)
    Shareware computer games - http://rainerdeyke.com
    "In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedMay 14, '01 at 9:06p
activeMay 15, '01 at 7:02p
posts6
users4
websitepython.org

People

Translate

site design / logo © 2022 Grokbase