An Introduction to Python __name__ == ‘__main__’ for Beginners – Python Tutorial

By | September 17, 2019

In most python script, you may find code like: if __name__ == ‘__main__’:, What does this mean? In this tutorial, we will discuss this code and tell you how to use it.

Python __name__ == '__main__'

What is __name__?

__name__ is a special python variable, the aim of which is used to check whether or not the module is being
run by itself or others. Look at example code below.

File 1. pdftest5.py

The content of which is:

print(__name__)

File 2. pdftest6.py

The content of which is:

import pdftest5
print(__name__)

Run pdftest5.py

You will get result:__main__

Run pdftest6.py

You will get result:

pdftest5
__main__

From the result we will find:

If python script is run by itself, the __name__ will be __main__

If python script is run by other python script, the __name__ will be the model name of this python script.

Why use if __name__ == ‘__main__’ ?

To use if __name__ == ‘__main__’, we can avoid execute related codes in python script, which are only allowed to run by itself.

For example, we edit pdftest5.py and copy codes below into to it.

print(__name__)
if __name__ == '__main__':
    print("run pdftest5")

If you run pdftest5.py, you will get:

__main__
run pdftest5

If you run pdftest6.py, you will get:

pdftest5
__main__

Leave a Reply

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