How to pass a reference to the current module

Steven D'Aprano steve at
Sat Aug 4 03:46:52 CEST 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
        namespace = module.__dict__
    return namespace[name]


More information about the Python-list mailing list