What is if __name__ == ‘__main__’ ?

 

Module is simply Python file that has .py extension. Module can contain variables, functions, classes that can be reused.

In order to use module we need to import the module using import command. Check the full list of built-in modules in Python here https://docs.python.org/3.6/library.

The first time a module is loaded in to running Python script, it is initialized by executing the code in the module once. To know various ways of importing modules visit here: https://docs.python.org/3.6/tutorial/modules.html

if __name__ == ‘__main__’:

We see if __name__ == ‘__main__’: quite often. Let’s see what this actually is.

__name__ is global variable in Python that exists in all namespaces. It is attribute of module. It is basically the name of the module as str (string) type.

Show Me Code:

Create a file named ‘mymath.py’ and type the following code and save it. We have defined a simple mathematical square method here.

screenshot-from-2016-09-30-12-51-33

Now create another file named ‘result.py’ in the same directory and type the following code and save it.

screenshot-from-2016-09-30-12-57-10

Now on terminal run the program with ‘python3 result.py’
fotoflexer_photo

Here we have defined a method in a module and using it in another file.

Now let’s look into if __name__ == ‘__main__’:

Open the ‘mymath.py’ file and edit it as given in following:

screenshot-from-2016-09-30-13-56-50

Leave ‘result.py’ unchanged.

Now on your terminal run ‘result.py’. 

fotoflexer_photo1

Here we have imported the module mymath. The variable __name__ is set to the name of the module that is imported.

Now on terminal run ‘mymath.py’

fotoflexer_photo3

We have run the file mymath.py as program itself. And you can see here the variable __name__ is set to the string “__main__”.
And we have checked if __name__ == “__main__” is True execute the following instructions which means if the file is run as standalone program itself execute the following instructions.

If you do  print(type(__name__)) in the program, you will see it returns ‘str’ (string) type.

Happy Coding!

4 thoughts on “What is if __name__ == ‘__main__’ ?

Leave a comment