Function getting a reference to its own module

Steven D'Aprano steve at
Sun Sep 14 11:29:55 CEST 2008

I have a function that needs a reference to the module object it is 
defined in. (For the reason why, if you care, see the thread "doctest not 
seeing any of my doc tests" from a week ago.) I know of two ways to deal 
with this problem, both of which feel unsatisfactory to me. Assume the 
name of the module is "Mod", then I can do either of these:

def foo():
    import Mod

Disadvantage: If I change the name of the module, I have to remember to 
change the name of the module reference in foo() twice.

def foo():
    modname = foo.__module__
    module = __import__(modname)

Disadvantage: if I change the name of the function, I have to remember to 
change the reference to itself, but at least both changes are right next 
to each other.

Assume that changing the function name or the module name are both 
equally likely/unlikely.

Which do other people prefer? Which seems "better" to you? Are there any 
other alternatives?


More information about the Python-list mailing list