Python – Concept of __name__ & __main__

__name__ is an built-in variable and it will return the name of the module. And module is nothing but a python file which contains python definition and statements. If you want to know in which module you are working then you can use this variable “__name__” and you can find out.

__main__ is a module which will execute the top level code so this “__name__“. So, the variable will set to “__main__” when you will execute your program as the main program. If your file being imported by some other module then name will be assigned to the module name.

For better understanding, lets take two examples:

Let’s create two python file : one.py and two.py

#File one.py

def add(a,b):
    return a+b

print(add(10,5))

#OUTPUT
15
#File two.py

import one
print(one.add(10,2))

#OUTPUT
15
12

So on executing the file two.py, what will you see as an output: 15 (which is sum of 10 and 5) and 12 (which is sum of 10 and 2).

Is this a correct response? because you just want to call add() method from one.py into the two.py. And perhaps you don’t want to print any result from one.py.

So, in this case you need to use some special condition:

__name__ == “__main__”

So, whenever you run this one.py python file as the main python file. So whenever you run this one.py file, then the value of __name__ becomes __main__.

If you import one.py file to another python file, let suppose in two.py. And then use the function from the first one.py file module. Then it will change the module name and so it will not execute the codes under __name__ == “__main__”.

#File one.py

def add(a,b):
    return a+b

if __name__ == "__main__":
    print(add(10,5))
#File two.py

import one
print(one.add(10,2))

#OUTPUT
12
Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial