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.
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.
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.
import <module_name> Thus, a module creates a separate namespace, as already noted.
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.
import __main__
But don't do this.
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:
__main__
module should provide all necessary data as parameters to a module1
function/class,import module2
in both __main__
and module1
.I think this would work:
import sys
main_mod = sys.modules['__main__']
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With