What is the expression 'if __name__ == "__main__"?

15

I notice that some scripts in Python , 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?

    
asked by anonymous 15.10.2015 / 21:10

3 answers

18

if __name__ == "__main__" tests whether the Python script file is running as the primary file or not. This is useful for avoiding certain behaviors if your script is imported as a module from another script.

Within this if , some behaviors such as tests, output values or special functionalities are usually placed.

To see how this works, try setting a .py file with only 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
>>>
    
15.10.2015 / 21:17
7

When the Python fault interpreter reads a source file, it executes all the code found in it. Before executing the code, it will set some variáveis special. For example, if the Python interpreter is executing this module (the source file) as the main program, it sets the special __name__ to have a __main__ value. If this file is imported from another module, __name__ will be set to the name of the other module.

source :)

    
15.10.2015 / 21:14
2

In practical terms, all code written within this expression will only be executed if the library is used directly, for example, if the file in question is executed in this way:

python ficheiro.py

The code inside the expression will be executed. Whereas if the library is imported by another module:

import ficheiro

The code inside the expression will not be executed.

    
25.10.2015 / 14:45