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

Arnaud Delobelle arnodel at googlemail.com
Wed Nov 12 13:20:35 EST 2008


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

In mymodule.py
--------------

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


That's it!

-- 
Arnaud



More information about the Python-list mailing list