how to get a reference to the "__main__" module

W

WH

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? The 'if' clause should work here. I am just curious if
we can use the above method.

Thanks,
-WH
 
S

Steven D'Aprano

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']
 
C

Chris Rebert

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
 
A

Aahz

'x' in getattr() should be a reference to the "__main__" module, right?
How to get it?

Just for the record, the best way to get a reference to __main__ is to
import it:

import __main__
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,067
Latest member
HunterTere

Latest Threads

Top