What does if __name__ == __main__ mean in Python

Introduction

Python programming language does not have a main function to mark the entry point of the program as in C++. Any Python script (i.e. module) can have executable code, function and class definitions. When a script is passed to the Python interpreter, the executable code gets run automatically. In other words, a module can be both a library (i.e. when imported) and a main script (i.e. when called directly). How is that related to our main question ? well, imagine the following two scenarios…

  • We developed a script and ended up writing some useful functions. We can easily import that script and use its functions in another script. That is cool but we need to find a way to prevent the executable code from running when the script is imported
  • We developed a library and included some code to test the library. We do not want the test code to run when the script is imported into another script

The built in global variable __name__ can help in such scenarios. Let us see how…

__name__ and __main__ in Python

__name__ is a built-in global variable which evaluates to the name of the current module. It is equal to __main__ if the script is run directly, otherwise the script is being imported. In this case, the variable __name__ carries the module name. Let us take an example…

Example

Assume we have the following Python code for some library…

Calling the library directly…

The output will be…

Assume we have a user program that uses the library…

If we run user.py…

We should get the following output…

That is it for today. Thanks for reading. Please use the comments section below for feedback.

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *