views:

118

answers:

2
+2  A: 
import inspect
def callers_module():
   module = inspect.getmodule(inspect.currentframe().f_back)
   return module
manifest
A: 

While inspect.getmodule works great, and I was indeed looking in the wrong place to find it, I found a slightly better solution for me:

def callers_module():
  module_name = inspect.currentframe().f_back.f_globals["__name__"]
  return sys.modules[module_name]

It still uses inspect.currentframe (which I prefer over the exactly identical sys._getframe), but doesn't invoke inspect's module-filename mapping (in inspect.getmodule).

Additionally, this question inspired an interesting way to manage __all__:

from export import export

@export
class Example: pass

@export
def example: pass

answer = 42
export.name("answer")

assert __all__ == ["Example", "example", "answer"]
Roger Pate
Now I wish I could make modules callable and simplify the above example: http://stackoverflow.com/questions/1060796/callable-modules
Roger Pate