Function getting a reference to its own module

Arnaud Delobelle arnodel at googlemail.com
Sun Sep 14 11:43:45 CEST 2008


On Sep 14, 10:29 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> 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
>     process(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)
>     process(module)
>
> 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?

What about something like:

    sys.modules[__name__] ?

--
Arnaud




More information about the Python-list mailing list