What is if name = = "main":?

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's the difference?
  • why prefer one over the other?
  • what is it and how does it work?
 62
Author: IDis31, 2016-11-06

3 answers

This is intimately linked to how the Python interpreter works:

  • When the interpreter reads a code file, executes all the global code found in it . This involves creating objects for any defined function or class and global variables.

  • Every module (code file) in Python has a special attribute called __name__ that defines the namespace it is running in. It is used for uniquely identify a module in the import system.

  • "__main__" is the name of the scope in which the top-level code (your main program) is executed.

  • The interpreter 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 interpreter in the terminal with python my_modulo.py, double-clicking on it, running it in the interactive interpreter, etc ).

  • If the module is not called as the main program, but is imported from another module, the __name__ attribute becomes the name of the file itself.

Here you have the official documentation.

That is, if you have a file called mi_modulo.py, if we run 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 run directly or not (imported). if it has been executed as the main program the code is executed inside the conditional.

One of the reasons for doing so is that sometimes you write a module (a. py file) that can be run directly but that 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 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 a graphical interface example, but needless to say that when we import the module to use the widget we do not want a window to appear out there for the love of art. A real example in the framework Kivy :

With the use of the conditional we get the execution to be 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):

Create a module that we will call mi_modulo.py:

print("¡Hola desde mi_modulo.py!")

def hacer_algo():
    print("¡Soy una función y hago algo!")

if __name__ == "__main__":
    print('Ejecutando como programa principal')
    hacer_algo()

print("¡Adiós desde mi_módulo.py!")  # Debajo del condicional pero fuera del mismo

In the same folder you create another module that we will call principal.py

import mi_modulo

print("¡Hola desde principal.py!")
mi_modulo.hacer_algo()
print("¡Adiós desde principal.py!")

If you run the script mi_modulo.py directly:

$ python mi_modulo.py

The value of __name__ will be "__main__" and the block inside the if __name__ == “__main__”: will be executed:

Hello from mi_modulo.py!
Running as main program
I am a function and I do something!
Goodbye from mi_modulo.py!

If we execute the file principal.py that uses mi_modulo.py importing it does not fulfill the condition if __name__ == “__main__” so only the global code is executed (the initial print and the function object hacer_algo is created in memory). The function only executes when we call it from the main module:

Hello from mi_modulo.py!
Goodbye from mi_modulo.py!
Hello from principal.py!
I am a function and I do something!
Goodbye from principal.py!

Now let's change the script mi_modulo.py by:

print("¡Hola desde mi_modulo.py!")

def hacer_algo():
    print("¡Soy una función y hago algo!")

hacer_algo()
print("¡Adiós desde mi_modulo.py!"))

If we run it as the main program the result is the same as before, but if we run now principal.py we get this:

Hello from mi_modulo.py!
I am a function and I do something!
Goodbye from mi_modulo.py!
Hello from principal.py!
I am a function and I do something!
Goodbye from principal.py!

The thing is that the import we execute all the code of the imported module, including the function call that is now not wrapped in the conditional. Once imported the main module calls the imported function again.

In short, the two ways you put are valid if you run the script always as the main program, if you use it also importing it you do not usually want Code to be executed if you do not call a function yourself and that is the reason to use if __name__ == “__main__”:

 91
Author: FJSevilla, 2020-04-03 17:24:46

The instruction if, of type:

if __name__ == “__main__”:
    # (bloque cosas dentro)

Serves to isolate or decouple the execution of the (bloque de cosas dentro) within one program (condition true), a when you fully import that program into another.

In that case, when running this other, the (bloque de cosas dentro) for having false condition.

So I can do different things with the same program (direct vs imported).

 8
Author: user37950, 2017-06-03 08:02:07

Is the main function of the program is used to initialize the program for this you simply do the following from the cmd:

python tuejemplo.py

And the program is initialized and executed. On the other hand, because using this method because you can start it or when you want to add it as a module then the program will not start I think that's the only difference.

 5
Author: Perl, 2016-11-06 19:00:54