Making "import" *SLIGHTLY* more verbose?

Bengt Richter bokr at oz.net
Tue Oct 25 22:25:02 EDT 2005


On Tue, 25 Oct 2005 15:34:37 -0700, Steve Juranich <sjuranic at gmail.com> wrote:

>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__ =3D __builtins__.__import__
>
>def noisy_import(name, globals =3D globals(), locals =3D locals(), fromlist=
> =3D []):
>    printit =3D name not in sys.modules
>    mod =3D __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__ =3D 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
You want to go beyond just teasing, and tell us what "particular class"? ;-)

>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.
The imp module has a lot of info, and some example code that
might be useful.

I'm suspicious of the default values you provide in your noisy_import though.
They are all mutable, though I guess nothing should mutate them. But will they
be valid for all the contexts your hook will be invoked from? (Or are they actually
useless and always overridden?)

Regards,
Bengt Richter



More information about the Python-list mailing list