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

Joe Strout joe at strout.net
Tue Nov 11 23:10:26 EST 2008


I've been using docstring to exercise each of my modules, with code  
like this:

def _test():
	import doctest
	doctest.testmod()

if __name__ == "__main__":
	_test()


This works great when I execute each module by itself.  However, if I  
want to call mymodule._test() from somewhere else, it doesn't work,  
because doctest.testmod() tests the __main__ module instead of  
mymodule.  And of course changing the call to this doesn't work either:

	doctest.testmod(mymodule)

This actually works fine if I'm importing the module (with the  
standard name) somewhere else, but not when I'm executing it directly,  
or (I would guess) if the module is imported under a different name.

What I want to express is "doctest THIS module, right here, the one  
this code is in!"  But I can't find a clean way to do that.

I noticed that a function object has a __module__ attribute, that is a  
reference to the module the function is in. But that just pushes the  
problem back a step: how can a function get a reference to itself?

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.  Can  
someone share a clue?

Thanks,
- Joe






More information about the Python-list mailing list