The construct " if __name__ == '__main__' " in Python

Solution 1:

You should get in the habit of using this almost always.

Anything that comes after if __name__ == '__main__': will be run only when you explicitly run your file.

python myfile.py

However, if you import myfile.py elsewhere:

import myfile

Nothing under if __name__ == '__main__': will be called.

Solution 2:

A really simple example to understand this statement is the following:

Assume that we have the following Python script named: using_name.py:


# Filename: using_name.py

if __name__ == '__main__':
    print 'This program is being run by itself'
else:
    print 'I am being imported from another module'

Now, try to do the following two things and see what happens:


1) Run directly the script

python using_name.py

Result

This program is being run by itself

2) Import the script

python

import using_name

Result

I am being imported from another module