Making "import" *SLIGHTLY* more verbose?

Steve Juranich sjuranic at gmail.com
Tue Oct 25 18:34:37 EDT 2005


First of all, just let me say that I'm aware of the "-v" switch for
Python, and I don't want anything nearly that verbose.

I often long for the following behavior from Python when I'm running
interactively: When a new module is imported, I'd like the path to the
file providing the module to be printed out to the screen.  If the
module is already in sys.modules, then don't worry about printing
anything.

The best thing that I can think of to do is something like:

<python>
__builtins__.__real_import__ = __builtins__.__import__

def noisy_import(name, globals = globals(), locals = locals(), fromlist = []):
    printit = name not in sys.modules
    mod = __real_import__(name, globals, locals, fromlist)
    if printit:
        try:
            print '## Loading %s (%s)' % (mod.__name__, mod.__file__)
        except AttributeError:
            print '## Loading %s (built-in)' % mod.__name__
    return mod

__builtins__.__import__ = noisy_import
</python>

Which seems to work okay for basic kinds of modules, but doesn't quite
work right for modules that belong to a particular class.  Any
suggestions on what I might be missing here?  I would imagine that
this is a cookbook type thing, and if there are any references on how
to do this, I'd greatly appreciate it (I couldn't come up with the
right Google magic words).

Thanks in advance for any help.

--
Steve Juranich
Tucson, AZ
USA



More information about the Python-list mailing list