Damon
Damon

Reputation: 221

In Python, how can I access the namespace of the main module from an imported module?

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.

Upvotes: 22

Views: 9630

Answers (4)

tzot
tzot

Reputation: 95931

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.

Upvotes: 11

Pieter
Pieter

Reputation: 29

I think this would work:

import sys    
main_mod = sys.modules['__main__']

Upvotes: 2

laurent
laurent

Reputation: 908

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.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

import __main__

But don't do this.

Upvotes: 15

Related Questions