how to get a reference to the "__main__" module

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Wed Jun 9 01:41:03 EDT 2010


On Tue, 08 Jun 2010 22:29:04 -0700, WH wrote:

> Hi,
> 
> I want to use one of two functions in a script:
> 
> def func_one(): pass
> def func_two(): pass
> 
> func = getattr(x, 'func_'+number)
> func()
> 
> 'x' in getattr() should be a reference to the "__main__" module, right?
>  How to get it?  


# File test.py
def func_one():
    return "one = 1"

def func_two():
    return "two = 2"

if __name__ == '__main__':
    import __main__
    func = getattr(__main__, 'func_' + 'two')
    print func()

    import test
    print getattr(test, 'func_' + 'one')()


which works, but importing yourself can be tricky. Try taking the "if 
__name__" test out and running the script and see what happens.


This is probably a better way to solve your problem that doesn't rely on 
the module importing itself:


def func_one():
    return "one = 1"

def func_two():
    return "two = 2"

funcs = {'one': func_one, 'two': func_two}

print funcs['one']



-- 
Steven



More information about the Python-list mailing list