import inspect
def callers_module():
module = inspect.getmodule(inspect.currentframe().f_back)
return module
manifest
2010-01-04 17:50:39
import inspect
def callers_module():
module = inspect.getmodule(inspect.currentframe().f_back)
return module
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"]