0

I know you can check to see if a module is being run directly, as opposed to imported, by doing:

if __name__ == '__main__':

but is there a way to check if the module that imported or called this module is the __main__ module.

So essentially instead I am looking for the second level down from the __main__ module; some way to check if the name of module that imported the current module is __main__.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
asielen
  • 11
  • 2
  • 2
    You could look into [`inspect`](https://docs.python.org/2/library/inspect.html), but why do you want to know? Could you explain more about what you're doing; this is probably an [XY problem](http://meta.stackexchange.com/q/66377). – jonrsharpe Jan 23 '15 at 08:24
  • This has the potential to cause some weird behaviour. Say you have `main.py`, `submodule.py` and `utilities.py`, with `main` importing `submodule` and `utilities`, and `submodule` importing `utilities`. `utilities` will be imported by `submodule`, and will NOT be imported again by `main`. Probably better to restructure so that you don't have to rely on where a module gets imported. – zehnpaard Jan 23 '15 at 08:36
  • The reason I am looking for this is because I have noticed that when creating threads in multiprocessing (on PC with Python3.4) the modules seem to be reimported when each thread is created. (Note: this doesn't seem to happen in Python3.4 in OSX) I want to try to prevent the module from running initialization code when it is imported by the threads and only run the code when it is imported the first time by the main module. – asielen Jan 23 '15 at 08:43
  • So why won't you ask a question about that? sounds like an x-y problem – shx2 Jan 23 '15 at 08:47
  • 1
    @asielen. Hmmm. I suspect that you should do that initialization code in an explicit function call then, rather than having it happen automatically happen on import. – PM 2Ring Jan 23 '15 at 08:56
  • @PM2Ring, I tried that and thought I was onto something combining that with the run once decorator from http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python Still didn't work though in Windows. But it did sort of lead me in the right direction to discover this: http://stackoverflow.com/questions/9670926/multiprocessing-on-windows-breaks which I think has what I am looking for. – asielen Jan 23 '15 at 09:17

0 Answers0