python – What is the use of the expression 'if __name__ == "__main__"'?

Question:

I notice that some Python scripts, right at the end of the code, have the following expression:

if __name__ == "__main__":
   #faça alguma coisa aqui

What is the purpose of this?

Answer:

if __name__ == "__main__" tests whether the Python script file is running as the main file or not. This is useful to avoid certain behavior if your script is imported as a module of another script.

Inside this if usually some behaviors such as tests, output values ​​or special features.

To see how this works, try defining a .py file with just the following:

print(__name__)

Save the file and run it as:

python meuteste.py

The output should be:

__main__

Now open the Python console and import the file. The output should be:

Python 2.7.2+ (default, Oct 15 2015, 16:17:59)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import meuteste
meuteste
>>>
Scroll to Top