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

Arnaud Delobelle arnodel at
Wed Nov 12 19:20:35 CET 2008

Joe Strout <joe at> writes:

> 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?

There isn't.  There was a proposal for one but it was rejected.
Nevertheless I think you can achieve this very easily.


def _test():
    import doctest
    import mymodule

That's it!


More information about the Python-list mailing list