Does Python Execute Imports On Importation
Lets say I have a module named module1 with the following: def main(): print 'K DawG' main() and a module2 with only this line: import module1 What basically happens is, whe
Solution 1:
Yes, of course a script is executed when it's imported. That's a fact you cannot change except by using a different programming language.
The solution is usually this:
if __name__ == '__main__':
main()
That way it's only executed if you run it using python whatever.py
but not when importing it.
To be more detailed on what happens during an import:
If the module is already in sys.modules
, that entry will be returned. Otherwise the module's code is executed and the globals from that file stored in the sys.modules
entry. So only the first time you import a module its code is executed.
Post a Comment for "Does Python Execute Imports On Importation"