DEV Community


Posted on

What does if __name__ == '__main__': do in Python?

What does if __name__ = '__main__' mean?

You can sometimes see this in Python script, in general this is where your Python program starts.

In many other languages, the computer program starts with a main() function. That can be the case in Python too.

main value

Let us do a quick exercise in order to grasp the specifics of the main function and the if statement.

print("module_name :{}".format(__name__))

Run the Python file and execute the file as python3 script

The outcome of the app in this example states that the variable name has a main value.

>>> print("module_name :{}".format(__name__))
module_name :__main__

So what is this main?

What does if name == "main": do?

When the above condition is tested, it must be verified whether the file is run directly by or imported by python.

The explanation demonstrates this.

    def main():
        print("module_name :{}".format(__name__))

    if __name__ == "__main__":
        print("run from import")

That's because you can import any Python script but most of the times you only want access to the functions

python main function

Like import math shouldn't execute sin, cos, pow etc automatically, you import it because you want it available.

If you are new to Python, I suggest this book

Top comments (0)