How can a function know what module it's in?

Joe Strout joe at strout.net
Wed Nov 12 16:10:27 CET 2008


On Nov 11, 2008, at 9:49 PM, Rafe wrote:

>>> I'm sure there is a magic identifier somewhere that lets a code get
>>> a reference to its own module, but I haven't been able to find it.
>
> import sys
> this_module = sys.modules[__name__]

Beautiful!  Thanks very much.  For the archives, here is my standard  
module-testing idiom now:

def _test():
	import doctest, sys
	doctest.testmod(sys.modules[__name__])

if __name__ == "__main__":
	_test()

Now, when I execute the module directly, it will test itself; and if I  
need to test it from the outside (for example, under pdb) I can import  
the module and then run themodule._test().

To whom should I make the suggestion that this go into doctest docs?

Cheers,
- Joe




More information about the Python-list mailing list