What does the if __name__ == "__main__": do in Python?

PythonServer Side ProgrammingProgramming

When the Python interpreter reads a source file, it executes all of the code found in it.

Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __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.

One reason for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.

For example, if you have 2 files one.py and two.py with the following code:


def func():
    print("func() in one.py")
print("Root of one.py")
if __name__ == "__main__":
    print("one.py is being run directly")
    print("one.py is being imported")


import one
print("Root of two.py")
if __name__ == "__main__":
    print("two.py is being run directly")
    print("two.py is being imported")

Now if you run,

$ python one.py

You will get the output:

Root of one.py
one.py is being run directly

But if you run,

$ python two.py

You will get the output:

Root of in one.py
one.py is being imported
Root of in two.py
func() in one.py
two.py is being run directly
Updated on 10-Jun-2020 14:03:33