How to pass a reference to the current module

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Fri Aug 3 21:46:52 EDT 2007


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]


-- 
Steven.




More information about the Python-list mailing list