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

Asked

Viewed 3,838 times

20

I notice some scripts on Python, at the very end of the code, have the following expression:

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

What’s the point of this?

4 answers

20


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

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

To check how this works, try setting a file .py with only the following:

print(__name__)

Save the file and run it as:

python meuteste.py

The exit 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
>>>

8

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

source :)

  • Just a correction, in the answer you linked says: If this file is being imported from another module, __name__ will be set to the module's name. you interpreted that the __name__ will receive the name of the other module, I was in doubt and tested, the result is that __name__ receives the name of the module itself.

2

In practical terms, all code written within that 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.

-5

if __main__ == '__name__': print(__main__)
  • When replying imagine that you are writing a technical document that aims to resolve a request. Be clear and explanatory, if possible add corroborative references to the content. Read [Answer].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.