Python si __name__ == __main__ explicado con ejemplos de código

Cuando un intérprete de Python lee un archivo de Python, primero establece algunas variables especiales. Luego, ejecuta el código del archivo.

Una de esas variables se llama __name__.

Si sigue este artículo paso a paso y lee sus fragmentos de código, aprenderá a usarlo if __name__ == "__main__"y por qué es tan importante.

Explicación de los módulos de Python

Los archivos de Python se denominan módulos y se identifican por la .pyextensión del archivo. Un módulo puede definir funciones, clases y variables.

Entonces, cuando el intérprete ejecuta un módulo, la __name__variable se establecerá como   __main__si el módulo que se está ejecutando fuera el programa principal.

Pero si el código está importando el módulo de otro módulo, entonces la __name__  variable se establecerá con el nombre de ese módulo.

Echemos un vistazo a un ejemplo. Cree un módulo de Python con nombre file_one.pyy pegue este código de nivel superior dentro:

# Python file one module print("File one __name__ is set to: {}" .format(__name__))

Al ejecutar este archivo, verá exactamente de lo que estábamos hablando. La variable __name__de este módulo se establece en __main__:

File one __name__ is set to: __main__

Ahora agregue otro archivo llamado file_two.pyy pegue este código dentro:

# Python module to import print("File two __name__ is set to: {}" .format(__name__)) 

Además, modifique el código de file_one.pyesta manera para que importemos el file_twomódulo:

# Python module to execute import file_two print("File one __name__ is set to: {}" .format(__name__)) 

Ejecutar nuestro file_onecódigo una vez más mostrará que la __name__variable en el file_oneno cambió y aún permanece establecida en __main__. Pero ahora la variable __name__in file_twose establece como su nombre de módulo, por lo tanto file_two.

El resultado debería verse así:

File two __name__ is set to: file_two File one __name__ is set to: __main__ 

Pero ejecute file_twodirectamente y verá que su nombre está configurado como __main__:

File two __name__ is set to: __main__ 

La variable __name__del archivo / módulo que se ejecuta será siempre __main__. Pero la __name__variable para todos los demás módulos que se están importando se establecerá con el nombre de su módulo.

Convenciones de nomenclatura de archivos de Python

La forma habitual de usar __name__y se __main__ve así:

if __name__ == "__main__": Do something here 

Veamos cómo funciona esto en la vida real y cómo usar estas variables.

Modificar file_oney file_twolucir así:

file_one:

# Python module to execute import file_two print("File one __name__ is set to: {}" .format(__name__)) if __name__ == "__main__": print("File one executed when ran directly") else: print("File one executed when imported") 

file_two:

# Python module to import print("File two __name__ is set to: {}" .format(__name__)) if __name__ == "__main__": print("File two executed when ran directly") else: print("File two executed when imported") 

Nuevamente, al ejecutarlo file_one, verá que el programa reconoció cuál de estos dos módulos es __main__y ejecutó el código de acuerdo con nuestras primeras if elsedeclaraciones.

El resultado debería verse así:

File two __name__ is set to: file_two File two executed when imported File one __name__ is set to: __main__ File one executed when ran directly 

Ahora ejecute file_twoy verá que la __name__variable está configurada en __main__:

File two __name__ is set to: __main__ File two executed when ran directly 

Cuando se importan y ejecutan módulos como este, sus funciones se importarán y se ejecutará el código de nivel superior.

Para ver este proceso en acción, modifique sus archivos para que se vean así:

file_one:

# Python module to execute import file_two print("File one __name__ is set to: {}" .format(__name__)) def function_one(): print("Function one is executed") def function_two(): print("Function two is executed") if __name__ == "__main__": print("File one executed when ran directly") else: print("File one executed when imported") 

file_two:

# Python module to import print("File two __name__ is set to: {}" .format(__name__)) def function_three(): print("Function three is executed") if __name__ == "__main__": print("File two executed when ran directly") else: print("File two executed when imported") 

Ahora las funciones se cargan pero no se ejecutan.

Para ejecutar una de estas funciones, modifique la if __name__ == "__main__"parte de file_onepara que se vea así:

if __name__ == "__main__": print("File one executed when ran directly") function_two() else: print("File one executed when imported") 

Al ejecutar file_one, debería ver que debería ser así:

File two __name__ is set to: file_two File two executed when imported File one __name__ is set to: __main__ File one executed when ran directly Function two is executed 

Además, puede ejecutar funciones desde archivos importados. Para hacer eso, modifique la if __name__ == “__main__”parte de file_onepara que se vea así:

if __name__ == "__main__": print("File one executed when ran directly") function_two() file_two.function_three() else: print("File one executed when imported") 

Y puede esperar un resultado como este:

File two __name__ is set to: file_two File two executed when imported File one __name__ is set to: __main__ File one executed when ran directly Function two is executed Function three is executed 

Ahora digamos que el file_twomódulo es realmente grande con muchas funciones (dos en nuestro caso), y no desea importarlas todas. Modificar file_twopara verse así:

# Python module to import print("File two __name__ is set to: {}" .format(__name__)) def function_three(): print("Function three is executed") def function_four(): print("Function four is executed") if __name__ == "__main__": print("File two executed when ran directly") else: print("File two executed when imported") 

And to import the specific functions from the module, use the from import block in the file_one file:

# Python module to execute from file_two import function_three print("File one __name__ is set to: {}" .format(__name__)) def function_one(): print("Function one is executed") def function_two(): print("Function two is executed") if __name__ == "__main__": print("File one executed when ran directly") function_two() function_three() else: print("File one executed when imported")

Conclusion

There is a really nice use case for the __name__ variable, whether you want a file that can be run as the main program or imported by other modules. We can use an if __name__ == "__main__" block to allow or prevent parts of code from being run when the modules are imported.

When the Python interpreter reads a file, the __name__ variable is set as __main__ if the module being run, or as the module's name if it is imported. Reading the file executes all top level code, but not functions and classes (since they will only get imported).

Bra gjort! (That means "Well done" in Swedish!)

Check out more articles like this on my freeCodeCamp profile, Medium profile, and other fun stuff I build on my GitHub page.