__name__==__main__
Vijithkumar Vijayan
DST-INSPIRE fellow | Ph.D. Scholar in Bioinformatics | Blogger | YouTuber
#A python module is a python program, for eg: "helloworld.py". #This python program could be run as itself from the terminal window or it could also be imported as a module in another python script, in the format "import module"
#Every python program has an attribute called __name__. This __name__ is a variable whose value is "the name of the module". That means the value of the attribute is generally set to the name of the module. For example if you import "random" module as "import random", the __name__(dunder main) is set as "random".
#in a python program if the __name__ variable is set to __main__ as in a conditional, and the set of instructions are provided under the conditional like
# if __name__==__main__:
# ? print("text")
# ? func()
#This function call will be executed only if the program is run as its own program, not when imported in another program. Which means the instructions will be executed only when the main program is run from the terminal.
#If the module is imported from another python program, then the __name__ is set to the "name of the module" not to "__main__"
#for example, let's run a code.
test_value=100
a=54
b=45
#define a function
def func(a, b):
? ? print("value of __name__", __name__)
? ? return a+b
if __name__=="__main__":
? ? print("This will be executed if run as main program")
? ? print("value of __name__", __name__)
? ? func(a, b)
#When this program is run
#The output is:
领英推荐
This will be executed if run as main program
value of __name__ __main__
value of __name__ __main__
Here the if conditional was satisfied as the __name__ is set to __main__.
#Now if we try to import this module in another program.
#We can import using the "import module" statement.
#Let's save the "if __name__==__main__:" module as "helloworld.py"
#and
import helloworld
value=helloworld.test_value
function_call=helloworld.func(84, 40)
name=helloworld.__name__
print(value)
print(function_call)
print(name)
#The result is
100
value of __name__ helloworld
124
helloworld
#The import method has failed to execute the "if conditional". Because when the code is imported as a module in another script the __name__ attribute set to the name of the module instead of the "__main__".