Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 492
Damon Avatar asked Sep 06 '10 00:09

Damon


People also ask

How do I find the namespace in Python?

Use vars() to convert your namespace to a dictionary, then use dict. get('your key') which will return your object if it exists, or a None when it doesn't.

How do you access namespace variables in Python?

To get access to local namespace dict you can call locals() or if you want to access any object's namespace call vars(objname) . Inside function if you call locals() or vars() you will get currently visible namespace as dictionary and should not be modified.

Which command creates a separate namespace for the imported module S?

import <module_name> Thus, a module creates a separate namespace, as already noted.

What is namespace of module in Python?

In Python-speak, modules are a namespace—a place where names are created. And names that live in a module are called its attributes. Technically, modules correspond to files, and Python creates a module object to contain all the names defined in the file; but in simple terms, modules are just namespaces.


4 Answers

import __main__

But don't do this.

like image 113
Ignacio Vazquez-Abrams Avatar answered Oct 04 '22 16:10

Ignacio Vazquez-Abrams


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.
like image 38
tzot Avatar answered Oct 04 '22 16:10

tzot


I think this would work:

import sys    
main_mod = sys.modules['__main__']
like image 21
Pieter Avatar answered Oct 04 '22 18:10

Pieter


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.

like image 40
laurent Avatar answered Oct 04 '22 16:10

laurent