Search code examples
pythonimportnestedprogram-entry-point

if __name__ == "__main__" on Imports


I'm working on two python files. Once I am done, I plan to call one from from another:

main.py
import os, re, time, logging, sys, subprocess, operator, datetime, pprint, dbfread, collections, calendar, xlwt, xlrd, errno, platform, stat
import subfile
# A long body of codes that does things

subfile.py
import os, re, time, logging, sys, subprocess, operator, datetime, pprint, dbfread, collections, calendar, xlwt, xlrd, errno, platform, stat
# Another long body of codes that does things

If I call main.py, I expect it to run subfile.py also. Occasionally, I will run subfile.py separately and would like for it to run normally on its own. Now, in subfile.py, should I nest the import commands under if __name__ == "__main__"?

subfile.py
if __name__ == "__main__": 
    import os, re, time, logging, sys, subprocess, operator, datetime, pprint, dbfread, collections, calendar, xlwt, xlrd, errno, platform, stat
# Another long body of codes that does things

Solution

  • If your motivation is to avoid multiple imports of the very same module, don't be afraid of that.

    Import of an already imported module is almost a no-op, basically just one lookup in the dict of modules.

    So there is no gain, just the downside of making the program little bit more complicated and less readable.