What is __name__ in Python
In Python, there is no main() function like in other programming languages. When the python program is given interpreted by the interpreter, the code at the 0th level is executed.
__name__ is one of the special variables provided by Python. It gets its value depending on how we execute the containing script. 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.
__name__ is a built-in variable which evaluates to the name of the current module. Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement
Lets see an example:
def myFunc(): print(' The value of __name__ is '+ __name__) def main(): myFunc() if __name__ =='__main__': main()
When we run the above Python script, initially the interpreter set __name__ to ‘__main__’. Then run the def statements for main and myFunc. Afterward, the condition with __name__ evaluates to true. Then execute the main() and the myFunc(). Finally returns ‘The value of __name__ is __main__’