What is if __name__ == “__main__” In Python
There is truly nice use case for the __name__ variable, regardless you need a file that can be run as the main program or imported by different modules. We can utilize an if __name__ == “__main__” block to allow or prevent parts of code from being run when the modules are imported.
At the point 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.
Consider the below code understand better and name it as my_module.py.
# file my_module.py x = 100 def hello(): print("i am from my_module.py") if __name__ == "__main__": print("Executing as main program") print("Value of __name__ is: ", __name__) hello()
To execute this module as main program by giving below code.
Executing as main program Value of __name__ is: __main__ i am from my_module.py
Here we created a new module and executed it as main program hence the value of __name__ is set to ‘__main__’. Hence, the if condition is satisfied and the function hello() gets called.
Now create a new file called module.py and use the below code:
import my_module print(my_module.x) my_module.hello() print(my_module.__name__)
100 i am from my_module.py my_module
As you can see the result, the if statement in my_module failed to execute because the value of __name__ is set to ‘my_module’.