How to pass a reference to the current module

James Stroud jstroud at
Sat Aug 4 06:06:23 CEST 2007

Paul Rubin wrote:
> James Stroud <jstroud at> writes:
>>      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).
> I'm still completely confused.  Does FunctionUser know what module the
> user functions are supposed to come from?  Could you give an example
> of what you want the actual contents of those 3 modules to look like?
> E.g.:
>       import FunctionUser
>       def foo(x):
>           print x+3
>        def do_something_with (module, funcname, *args, **kw):
>          func = getattr(module, funcname)
>          func (*args, **kw)
>        import UserDefined1, FunctionUser
>        # the following should print 10
>        FunctionUser.do_something_with(UserDefined1, 'foo', 7)
> I don't think the above is quite what you want, but is it somewhere
> close?

Its very close. However, there is the possibiltiy that and are the same module. In such a case I'm guessing that I 
need to resort to the gymnastics of frame inspection I mentioned 
earlier. The problem is when this combination of possibilities exists:

    1. is named without the .py (e.g. `main`) as would be
       the convention for "programs"), and is not a true python
       module as a result--perhaps python has a mechanism for
       importing such files?
    2. foo is defined in `main`

Possibility two (even when it is a properly named module) sets the stage 
for a circular import, but I believe in python this is not entirely 
worrisome. However, the combination above makes it difficult to pass a 
reference to the `main` namespace without some sort of introspection. 
Ideally, I would prefer to not require the user to provide some mapping 
as it detracts from the convenience of the API. For example:

    from UserDefined1 import some_function
    def foo(): [etc.]
    def doit(): [etc.]
    mapping = {
                'foo' : foo,
                'doit' : doit,
                'some_function' : some_function

The idea would be that the above mapping would be specified in the 
configuration file:

param1 = float
param2 = 4

__module__ = 'UserDefined1'
__function__ = 'doit'
param1 = str
param2 = 30.0

param1 = float
param2 = float



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

More information about the Python-list mailing list