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

Joe Strout joe at
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

if __name__ == "__main__":

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?

- Joe

More information about the Python-list mailing list