I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code:
foo.py:
The "currently executing module" clearly is foo, as that's what contains the function currently running - I think a better description as to what you want is the module of foo's immediate caller (which may itself be foo if you're calling a f() from a function in foo called by a function in bar. How far you want to go up depends on what you want this for.
In any case, assuming you want the immediate caller, you can obtain this by walking up the call stack. This can be accomplished by calling sys._getframe, with the aprropriate number of levels to walk.
def f():
caller = sys._getframe(1) # Obtain calling frame
print "Called from module", caller.f_globals['__name__']
[Edit]: Actually, using the inspect module as suggested above is probably a cleaner way of obtaining the stack frame. The equivalent code is:
def f():
caller = inspect.currentframe().f_back
print "Called from module", caller.f_globals['__name__']
(sys._getframe is documented as being for internal use - the inspect module is a more reliable API)