__name__ __main__
suggest changeThe special variable __name__ is not set by the user. It is mostly used to check whether or not the module is being run by itself or run because an import was performed. To keep a module from running certain parts of its code when it is imported, check if __name__ == '__main__'.
Let module1.py be just one line long:
import module2
The import name is module2, not module2.py. import module2.py looks up a submodule named py inside a package named module2.
And let’s see what happens, depending on module2.py
Situation 1
module2.py
print('hello')
Running module1.py will print hello
Running module2.py will print hello
Situation 2
module2.py
if __name__ == '__main__':
print('hello')
Running module1.py will print nothing
Running module2.py will print hello
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents