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.
Asked
Active
Viewed 9,207 times
22
-
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 Sep 06 '10 at 02: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 Sep 06 '10 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 Dec 15 '12 at 20:33
-
Similar: [Accessing argparse arguments from the class](http://codereview.stackexchange.com/q/88655/15346) at CR SE – kenorb May 05 '15 at 12:01
4 Answers
15
import __main__
But don't do this.

Ignacio Vazquez-Abrams
- 776,304
- 153
- 1,341
- 1,358
-
7@Alcott: Because it can very easily turn your program into a pretzel. – Ignacio Vazquez-Abrams Jul 04 '14 at 05:06
-
2
11
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 amodule1
function/class, - or you should put everything that needs to be shared in another module, and import it as
import module2
in both__main__
andmodule1
.

tzot
- 92,761
- 29
- 141
- 204
1
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
- 888
- 8
- 13
-
1that is in fact the suggested method, although the OP seems to be looking for `__main__` – Zae Zoxol Mar 01 '19 at 04:44