Function getting a reference to its own module

Aaron "Castironpi" Brady castironpi at gmail.com
Sun Sep 14 18:10:07 CEST 2008


On Sep 14, 4:43 am, Arnaud Delobelle <arno... at googlemail.com> wrote:
> 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

You're just worried about changing the module's name in the future.
So use a global variable or function that you only have to change
once.

def Mod_mod( ):
   import Mod as Mod #<-- only one change needed
   return Mod

def foo( ):
   process( Mod_mod( ) )



More information about the Python-list mailing list