How to pass a reference to the current module

James Stroud jstroud at mbi.ucla.edu
Fri Aug 3 21:45:59 EDT 2007


Steven D'Aprano wrote:
> On Fri, 03 Aug 2007 17:22:40 -0700, 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.
> 
> 
> I second Carsten Haese's suggestion that instead of passing function
> names, you pass function objects, in which case you don't need the module.
> But perhaps you need some way of finding the function, given its name.
> 
> def get_function_from_name(name, module=None):
>     if module is None:
>         # use the current namespace
>         namespace = locals() # or globals() if you prefer
>     else:
>         namespace = module.__dict__
>     return namespace[name]
> 
> 

This assumes that get_function_from_name is defined in the same module 
as the function named by name. However, I want this:


      Module            Behavior
   ==============  ====================================================
    UserDefined1   Imports FunctionUser
    ThirdParty     Contains User Functions (May be ==UserDefined1)
    FunctionUser   do_something_with() and/or get_function_from_name()

So the name-to-function mapping is done in FunctionUser but the function 
is actually defined in UserDefined1 (or ThirdParty if ThirdParty is 
different than UserDefined1).

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list