Python If __name__ == “__main__”

There are two things which we can do with our script/program, either we run it directly or import it into another program. Suppose we have a my_module.py file, as shown below

To run the my_module.py file directly we write python my_module.py on the command line. But if we want to import this file, then we have to comment out the function() calling statement. Import file means we only want functions, classes etc. and no code execution statements like a function call from that file. Just let the user call these at his own will.

For example, import math only imports functions from the math.py file. It is up to us whether we call math.sin() or math.cos(). That’s why we should remove code execution statements before importing a file.

Problem: “Commenting out function call from the file which we want to import”. For large modules, this is seriously a headache.

Question: Can’t we do something to automate the above problem, meaning writing import should automatically comment out or remove the function call.

Solution: Python if __name__ == “__main__” statement.

Concept: Before executing the code, Python defines a few special variables. For example, if the Python interpreter is running that module (the source file) directly, 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 or file’s name.

So, what we do is write all the code execution statements inside if __name__ == “__main__” statement. When we run the file directly this condition is satisfied and the code is executed. While importing __name__ == file_name and not __main__  so the code is not executed.  Let’s see an example

Running the above hello.py file directly (F5 in shell or by command line), we get this output

Now, import this hello.py into another file say hi.py like as shown below

Running the above code gives the output shown below

Clearly, the func() is not executed while importing and this is what we want.

Now, you might have got some feeling about the Python if __name__ == “__main__” statement. Always use this. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

Leave a Reply