DEV Community

Lalit Kumar
Lalit Kumar

Posted on

What is __name__ in python

The variable name varies depending on the module you are in during the execution of the program. In the main module, its value will be equal to main.

title: "What is name in python"
tags: python

canonical_url: https://kodlogs.com/blog/2656/what-is-__name__-in-python

If you are in another imported module, then its value will be equal to the name of the main module. The if (name == main) test makes it possible to distinguish between the two cases.

This condition is used to develop a module that can both be executed directly but also is imported by another module to provide its functions. You can insert into this block of code instructions intended for the case where the module is directly executed.

The python is a language that does not have a main () method, as it does in the C language. When you load a module, the code executed is the one located directly at the top level.

This condition, therefore, makes it possible to group together the instructions that we want to use in the case of direct execution of the module.

# myScript.py
if __name__ == __main__:
 print (my script is executed directly)
else
 print (my script is imported by another module)
# myOtherScript.py
import myScript
Enter fullscreen mode Exit fullscreen mode

By launching the manuscript script with the python command monScript.py, we get the message my script is executed directly. If, on the other hand, we run the myOtherScript script, which imports the myScript.py file, the message displayed will be my script is imported by another module.

Top comments (0)