__name__ and __main__ in Python

Ankit Deshmukh
TechGannet
Published in
2 min readJul 7, 2018

We often use if __name__ == “__main__”: in python programming. So,what does it mean ?

Let’s consider a file name sample.py . Command to run a python script is:

python sample.py

So, whatever is at zero indentation level gets executed. Functions and classes that are defined are, well, defined, but none of their code runs.

If the python interpreter is running the source file as the main program, it sets the special __name__ variable to value “__main__”. A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.

#sample.pydef my_function():
print("I am inside function")
print("Outside function")
# We can test function by calling it.
#my_function()
if __name__ == "__main__":
print("Executed when invoked directly")
else:
print("Executed when imported")
Output:
Outside function
Executed when invoked directly

As we executed sample.py directly __name__ variable will be __main__. So, code in this if statement will only run if that module is the entry point to your program.

If the code is being imported into another module, the various function and class definitions will be imported, but the main() code won’t run.

Consider two .py files:

#first.py
def func():
print("func() in first.py")
print("top-level in first.py")if __name__ == "__main__":
print("first.py is being run directly")
else:
print("first.py is being imported into another module")
#second.pyimport firstprint("top-level in second.py")
first.func()
if __name__ == "__main__":
print("second.py is being run directly")
else:
print("second.py is being imported into another module")

When you run second.py file, you will get following output:

Output:top-level in first.py
first.py is being imported into another module
top-level in second.py
func() in first.py
second.py is being run directly

In this case, we are importing module first and hence __name__ equals “first” instead of “__main__” and else block get executed from first.py .

That’s it!

Happy Coding!

--

--