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>