how to get a reference to the "__main__" module

Chris Rebert clp2 at rebertia.com
Wed Jun 9 01:42:10 EDT 2010


On Tue, Jun 8, 2010 at 10:29 PM, WH <whzhao at gmail.com> 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?

from sys import modules
__main__ = modules["__main__"] # or call the variable whatever you want
assert __main__.__dict__ is globals() # purely for pedagogy
func = getattr(__main__, 'func_'+number)

Of course, in your particular case, the code can be simplified to
avoid getattr() altogether:

func = globals()['func_'+number]

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list