The purpose of this blog is to happily share my learning and ideas to help people, who actively seek solutions for the day-to-day problems faced.

Recent Posts

Python: __name__ == '__main__' - Explained

In the Python world, most often we see the statement,

if __name__ == '__main__':

Ever wonder what's the actual use of this ?

__name__ == '__main__'

Long story short, when you want to run a python module directly, before executing the actual program the python interpreter sets the special variable __name__ equals to a value __main__ 

This results in the execution of a program starting with __main__, nothing but a entry point similar to JAVA

But whereas when you import the module into another module then by default the python interpreter sets the special variable __name__ equals to the value of module name. By this it avoids the direct execution of __main__ entry point.

Programmers use this feature wisely to set a conditional statements in their program to execute certain set of blocks when run directly and ignores the same when imported by another module.

Example:
Please click on the below git hub links for example explained using python code,

2 comments:

  1. Good one !!! Learned new stuff for today . Would you post something related to flask modules ?

    ReplyDelete
    Replies
    1. Thanks Heisenberg. Glad that it helps you for your learning. I haven't used flask framework before so can't comment on it but I am planning to post useful contents on Django framework in the near future.

      Delete