Site icon Meccanismo Complesso

What is if __name__ == “__main__” and why use it

For those who program in Python, they will be able to see the following construct within many codes, especially in the final part:

 if __name__ == "__main__":  

followed by a series of instructions enclosed in the indentation. What is it for? Why is it so common?

Before executing the code, the Python interpreter reads the source code and defines some special global variables, including the __name__ variable to which the name of the main module being executed is assigned. A module is a file containing definitions and declarations in Python. The file name is the name of the module without the .py suffix.

If the interpreter is executing that module as the main program, it will set the special __name__ variable to have an __main__ value. If this file is imported from another module, then __name__ will be set with the module name.

Example

Let’s look at a direct example to better understand the thing. Write the code below and save it as aModule.py

print("This part is always executed")

if __name__ == "__main__": 
    print("This part is executed when this file is invoked directly.")
 else: 
    print("This part is executed when this file is imported as module.") 

Now let’s see how we can invoke them in both cases.

python amodule.py

And in the second case write the code below and save it as importModule.py

import aModule

print("done") 

Conclusions

As you can see in the two cases the behavior is completely different. In fact, we have defined a .py file as a module. This is because in the file we have a part of the code as classes and functions, which are generally developed to be reused elsewhere. So with the construct seen in the article it is possible to use, or reuse elsewhere, differentiating the behavior. Leaving in the local “main“, a part of the implementation valid only in the context of the file seen by itself and not as a module.

Exit mobile version