views:

106

answers:

5

Specifically, I need to get at some objects and globals from the main module in an imported module. I know how to find those things when the parent module wants some particular thing from a child module, but I can't figure out how to go in the other direction.

A: 

Have you tried using the global keyword?

See the documentation.

Ink-Jet
No, this lets you rebind a module-scope name. This does nothing to let you get at another module.
Ignacio Vazquez-Abrams
Haha, i completely read the question wrong. My bad.
Ink-Jet
-1: you should remove this answer, or edit it.
ΤΖΩΤΖΙΟΥ
+5  A: 
import __main__

But don't do this.

Ignacio Vazquez-Abrams
A: 

Not sure if it is a good practice but maybe you could pass the objects and variables you need as parameters to the methods or classes you call in the imported module.

laurent-rpnet
A: 

I think this would work:

import sys    
main_mod = sys.modules['__main__']
Pieter
This is equivalent to `import __main__ as main_mod`.
Ignacio Vazquez-Abrams
+1  A: 

The answer you're looking for is:

import __main__

main_global1= __main__.global1

However, whenever a module module1 needs stuff from the __main__ module, then:

  • either the __main__ module should provide all necessary data as parameters to a module1 function/class,
  • or you should put everything that needs to be shared in another module, and import it as import module2 in both __main__ and module1.
ΤΖΩΤΖΙΟΥ