Re: [Tutor] reference to main module
Magnus Lycka
magnus at thinkware.se
Thu Dec 11 09:26:35 EST 2003
Luiz Siqueira Neto wrote:
> I discovery the answer, take a look:
>
> import sys
>
> main = sys.modules['__main__']
>
> # now I can call some function on the fly
> # Ex:
>
> def test():
> print 'yessss'
>
> def testStart(funct):
> getattrib(funct)()
>
> # Example using it
>
> testStart('test')
Here I get "NameError: global name 'getattrib' is not defined"
If you are in the same scope, you can do:
>>> def x():
print 'Hello'
>>> vars()['x']()
Hello
If your idea is to access code in the main module from
a submodule imported directly or indirectly by __main__,
I advice against it. Creating mutual dependencies between
modules like that is a bad practice, and a programmer of
one module does not expect that an *imported* module
expects to find certain functions, or calls code, in the
*importing* module.
If the submodule need something from the main module,
the main module should pass it in as a parameter in a
call, or possibly set a variable in the submodule.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus at thinkware.se
More information about the Tutor
mailing list