It is common to find code with this form:
def hacer_algo():
print("algo")
if __name__ == "__main__":
hacer_algo()
Instead of, for example:
def hacer_algo():
print("algo")
hacer_algo()
We also notice that the variable __name__
is not initialized by us, but exists in the environment.
- What is the difference?
- Why prefer one over the other?
- What is it and how it works?
This is closely linked to the way the Python interpreter works:
When the interpreter reads a code file, it executes all the global code found in it . This involves creating objects for any function or class defined and global variables.
Every module (code file) in Python has a special attribute called
__name__
that defines the namespace in which it is running. It is used to uniquely identify a module in the import system.On the other hand
"__main__"
, it is the name of the scope in which the higher level code (your main program) is executed.The shell passes the value of the attribute
__name__
to the string'__main__'
if the module is running as the main program (when you run it by calling the shell in the terminal withpython my_modulo.py
, double-clicking it, running it in the interactive shell, etc ).If the module is not called as the main program, but is imported from another module, the attribute
__name__
becomes the name of the file itself.Here is the official documentation.
That is, if you have a file called
mi_modulo.py
, if we execute it as the main program the attribute__name__
will be'__main__'
, if we use it by importing it from another module (import mi_modulo
) the attribute__name__
will be equal to'mi_modulo'
.Basically what you do using
if __name__ == “__main__”:
is see if the module has been executed directly or not (imported). If it has been executed as the main program, the code inside the conditional is executed.One of the reasons for doing this is that sometimes you write a module (a .py file) that can be executed directly but alternatively you can also import and reuse its functions, classes, methods, etc in another module.
In graphical frameworks, for example, it is common to generate an example of the use of the widget or widgets defined in that module that serves as an example of use and to test the module itself. If you run the module we will have an example graphical interface, but it goes without saying that when we import the module to use the widget we don't want a little window to appear for the sake of art. A real example in the Kivy framework :
With the use of the conditional we achieve that the execution is different when executing the module directly than when importing it from another module. Everything inside the conditional will be completely ignored by the interpreter when the module is imported, but not when it is run as the main module.
To see how it works you can try some code (following your own example):
You create a module that we will call
mi_modulo.py
:In the same folder you create another module that we will call
principal.py
If you run the script
mi_modulo.py
directly:the value of
__name__
will be"__main__"
and the block inside the will be executedif __name__ == “__main__”:
:If we execute the file
principal.py
it uses bymi_modulo.py
importing it, the condition is not met,if __name__ == “__main__”
so only the global code is executed (theprint
initial one and the function object is createdhacer_algo
in memory). The function is only executed when we call it from the main module:Now let's change the script
mi_modulo.py
to:If we execute it as the main program the result is the same as before, but if we execute it now
principal.py
we get this:What happens is that when importing we execute all the code of the imported module, including the call to the function that is now not wrapped in the conditional. Once imported the main module calls the imported function again.
In short, the two forms that you put are valid if you always execute the script as the main program, if you also use it by importing it, you usually do not want code to be executed if you do not call a function yourself and that is the reason for using
if __name__ == “__main__”:
the statement
if
, of the type:It is used to isolate or decouple the execution of the
(bloque de cosas dentro)
within a program (condition true), to when said program is totally imported into another.In that case, when executing this other one, it will not be executed
(bloque de cosas dentro)
because it has a false condition.This allows me to do different things with the same program (direct vs. imported).
It is the main function of the program, it is used to initialize the program, for this you simply do the following from the cmd:
And the program is initialized and executed. On the other hand, why use this method because you can start it or when you want to add it as a module then the program won't start I think that's the only difference.
Greetings to all in the community, I am going to contribute my grain of sand and explain it as simply as possible since I understand many people who, like me, at the time had not been able to understand this sentence or rather this condition.
if __ name__ == "__ main__":
This condition simply makes a query to check if the file being executed is the main or root file of the program. In Python the method __ name__ is the name of your file Example: calculator.py >> it will take __ name__ the name of your .py file and compare it with the __ main__ which will always be for python the main file, the file with the largest hierarchy.
But surely you wonder what is the point? Why am I going to waste time creating a condition if I want the program to run and that's it!
The answer to this is that we imagine an application with thousands of .py files and they assign you that project that someone else had already been doing, how would you know which is your root file? what is the beginning of everything? maybe you start with one that you think was the root and it is not!
I think this would be one of the main reasons (of the many reasons) why use if __ name__ == "__ main__"
It is not mandatory but it is a good practice to use it, I hope I have explained myself well and can contribute my grain of sand in the community. Greetings to all colleagues.