How to pass a reference to the current module

Carsten Haese carsten at uniqsys.com
Fri Aug 3 21:04:18 EDT 2007


On Fri, 2007-08-03 at 17:22 -0700, James Stroud wrote:
> Hello All,
> 
> Say I have this code:
> 
> 
> import AModule
> import ModuleUser
> 
> ModuleUser.do_something_with(AModule, 'some_function_name')
> 
> 
> But say the functions are defined in the same module that contains the 
> above code. I can imagine this hack:
> 
> 
> import AModule
> import ModuleUser
> 
> ModuleUser.do_something_with(AModule.__name__, 'some_name')
> 
> 
> Where AModule.__name__ could be substituted for __name__ under the 
> proper circumstances. Then, I would have this code in ModuleUser:
> 
> 
> import sys
> def do_something_with(modname, funcname):
>     afunction = sys.modules[modname].funcname
>     [etc.]
> 
> 
> Which is terribly ugly to me and makes for a pretty miserable API in my 
> opinion, requiring the programmer to type underscores.
> 
> 
> 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.
> 
> Thanks in advance for any suggestions.

I can't be too sure because you may have abstracted away too much of
what you're actually trying to accomplish, but it seems to me that
instead of passing a reference to the current module and a function
name, you should just pass a reference to the function that you want
do_something_with to call.

If I missed the point of your question, please describe less abstractly
what you're trying to do.

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





More information about the Python-list mailing list