I’m trying to get the exact module name that a module was imported with, from inside that module. Something like this:
def install():
print 'Local module name is %s' % __localModuleName__
And when I ran:
import myModule as mm
mm.install()
It would print
Local module name is mm
The script I’m trying to make installs itself into the external application Maya. Maya evaluates the string I pass it on demand in python. Right now, I’m trying to give Maya the string "myModule.run()". In this case, I have to know the exact name of myModule when myModule.install() is first run. __name__ isn’t specific enough if the user imports the module using import myModule as otherModule.
If there’s a better way to do this that doesn’t involve using the exact module name, I’d love to know. Like somehow converting a reference of myModule.run into a string I could store in Maya and later unpack. I’ve been trying to use the inspect module to find this information, but I keep finding situations where it doesn’t work and I have to go back and fiddle with it some more. It also seems kind of messy. This is what I’m using right now, which doesn’t work if myModule is called from __main__.
MODULENAME = None
fr = inspect.currentframe()
try:
while fr and not MODULENAME:
if fr.f_globals:
for name, obj in fr.f_globals.iteritems():
if hasattr(obj, '__file__') and inspect.ismodule(obj) and obj.__file__ == __file__:
MODULENAME = name
fr = fr.f_back
except:
pass
finally:
del fr
If there is no good solution, I plan to remove the above and tell the users that my module can’t be imported using import myModule as ....
An approach close to the one you are trying should work – bt it would be convolutd as you could verify.
Moreover, the “import module as othername” syntax is just a conveninet way of biinding the module object to another variable.
It is just the equivalent of
And your code should not depend on this for running.
However, in the global
sys.modulesdictionary, your module always shows up with its “real” name. Therefore, if you can pass an expression in a string to the host application, you should try to access your module within that dictionary – much less convoluted.Instead of passing:
guessedname.run()try passing:
And care not about the variable name that references your module in the running code. (this will even allow the user to do
from module import *for your code.