[Tutor] reference to main module
Luiz Siqueira
cybersamurai at terra.com.br
Thu Dec 11 18:57:56 EST 2003
Ops... sorry.
change getattrib to getattr. :)
And thanks about your help.
Magnus Lycka wrote:
>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.
>
>
>
>
More information about the Tutor
mailing list