Looking for python Answers? Try Ask4KnowledgeBase
Looking for python Keywords? Try Ask4Keywords

Python Language __name__ == '__main__'


Example

The 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 avoid your module to run certain parts of its code when it gets imported, check if __name__ == '__main__'.

Let module_1.py be just one line long:

import module2.py

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