What is __name__ in Python
The __name__ variable is a special Python variable. As you know there is no main() function in python. Indentation plays an important part in the execution of a python program. A python program can be executed on its on or it can be called as a module in other programs.
If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value “__main__”. If this file is being imported from another module, __name__ will be set to the module’s name.
Let’s see how this exactly works with the help of example. Consider two files file1.py and file2.py
print("File1 __name__ is %s" %__name__) if __name__ == "__main__": print("File1 is being run directly") else: print("File1 is being imported")
import file1 print("File2 __name__ is %s" %__name__) if __name__ == "__main__": print("File2 is being run directly") else: print("File2 is being imported")
Output:
As explained above, when file1.py is run directly, the interpreter sets the __name__ variable as __main__ and when it is run through file2.py by importing, the __name__ variable is set as the name of the python script, i.e. file1.