Re: __name__ of a module

Guido.van.Rossum@cwi.nl
Thu, 11 Nov 1993 22:06:01 +0100

> "module.__name__" contains the name string of < module 'module' >
> but it doesn't seem to be defined within the scope of
> the imported file itself, neither as "__name__", nor as
> "__main__.module.__name__" -- Although the latter, even
> if it DID work, would not be very useful for what I
> want - which is for a module to get it's own name.

I could change the initialization of a module to put __name__ in
the module's dictionary instead of implementing it in the getattr
function. But how useful is this? If it is only intended to win the
obfuscated Python contest, I don't know about it...

> Is there any way to do this ?
> Or any module equivalent of a method's 'self' ?

A 'self' would be problematic since it would create a circular
reference and thus prevent the module from being garbage-collected.

The following will work, by an exhaustive search of sys.modules:

def getmodulename():
# Finds the name of the current module
global _test
_test = [] # A unique new object
import sys
for modname in sys.modules.keys():
mod = sys.modules[modname]
# Note the use of the identify test 'is' below
if hasattr(mod, _test) and mod._test is _test:
del _test
return modname
return '???'

Oh, here's a way to find out from which directory a module was
imported (given its name :-):

def getmoddir(modname):
import sys
import os
for dirname in sys.path:
fullname = os.path.join(dirname, modname + '.py')
try:
open(fullname, 'r').close()
return dirname
except IOError:
pass
return '???'

(And instead of "del list[list.index(item)]" you can write
"list.remove(item)"...)

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>