inspect.getmodulename giving unexpected results

Thomas Jollans thomas at jollybox.de
Fri Sep 24 08:29:55 EDT 2010


On Friday 24 September 2010, it occurred to Geoff Bache to exclaim:
> Hi all,
> 
> I'm trying to examine some things in my stack. The information I get
> out of inspect.stack() gives file names and I would like to convert
> them to module names. I naturally assumes inspect.getmodulename would
> fix this for me.
> 
> Unfortunately, it doesn't seem to do that in some cases. Consider the
> following code:

It does behave as documented: it does not find package names, or investigate 
sys.modules

> ## file 'inspect_test'

rename this file to "inspect_test.py", and the filename will make sense to 
inspect.getmodulename, which should *then* return "inspect_test" instead of 
None.

> 
> #!/usr/bin/env python
> 
> import logging, inspect
> 
> print inspect.getmodulename(logging.__file__),
> inspect.getmodulename(__file__)
> 
> I hoped that this would print
> logging __main__
> 
> or at least
> logging inspect_test
> 
> but instead it prints
> __init__ None
> 
> which isn't very helpful, although it could technically be considered
> correct (I can go to the 'logging' directory and type "import
> __init__" but nobody ever does)
> 
> I guess I was hoping to get the names of the modules as they appear in
> sys.modules. Maybe there is some other way to do that? I can naturally
> write my own method to do this but wondered if I'm missing something
> here.

Not that I know of.



More information about the Python-list mailing list