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.
-
Well, okay, I assume that must be the case since I can't find any answers about this anywhere. The bottom line is I'm not concerned about reusing any of this code, I'm just trying to break this project apart into multiple files so it's more manageable to find what I'm looking for. I don't really know what I'm doing, honestly, so this has been a learning experience, but really I just want it to be easier to find the code I want to edit when I want to edit it.Damon– Damon2010-09-06 02:15:05 +00:00Commented Sep 6, 2010 at 2:15
-
I agree that there ought to be a way to pass parameters to a module when it is imported -- kind of like when you pass them to an object constructor. However I've never found a clean way to do this.martineau– martineau2010-09-06 10:14:28 +00:00Commented Sep 6, 2010 at 10:14
-
3I was looking for the exact same thing for the exact same reason, so it seems it's a typical newbie thing..sfranky– sfranky2012-12-15 20:33:03 +00:00Commented Dec 15, 2012 at 20:33
-
Similar: Accessing argparse arguments from the class at CR SEkenorb– kenorb2015-05-05 12:01:37 +00:00Commented May 5, 2015 at 12:01
Add a comment
|
4 Answers
import __main__
But don't do this.
2 Comments
Ignacio Vazquez-Abrams
@Alcott: Because it can very easily turn your program into a pretzel.
Charlie Parker
@IgnacioVazquez-Abrams can you expand on that?
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 amodule1function/class, - or you should put everything that needs to be shared in another module, and import it as
import module2in both__main__andmodule1.
Comments
I think this would work:
import sys
main_mod = sys.modules['__main__']
1 Comment
Ignacio Vazquez-Abrams
This is equivalent to
import __main__ as main_mod.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.
1 Comment
Zae
that is in fact the suggested method, although the OP seems to be looking for
__main__