How to pass a reference to the current module

Carsten Haese carsten at uniqsys.com
Fri Aug 3 21:19:31 EDT 2007


On Fri, 2007-08-03 at 17:53 -0700, James Stroud wrote:
> James Stroud wrote:
> > Basically, what I am trying to acomplish is to be able to do this in any 
> > arbitrary module or __main__:
> > 
> > 
> > funcname = determined_externally()
> > ModuleUser.do_something_with(AModule, funcname)
> > 
> > 
> > Ideally, it would be nice to leave out AModule if the functions were 
> > designed in the same namespace in which do_something_with is called.
> 
> 
> Is this the preferred way?
> 
> 
> import sys
> def do_something_with(funcname, amodule=None):
>    if amodule is None:
>      function = sys._getframe(1).f_locals[funcname]
>    else:
>      function = getattr(amodule, funcname)
>    [etc.]

This seems to confirm my suspicion that the do_something_with function
doesn't actually need a reference to the module, it only needs a
reference to the function to call.

Maybe your hurdle is how to obtain a reference to a function from the
current module when all you have is the name of the function in a
string. The answer to that would be "globals()[funcname]".

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list