How to understand if __name__ =='__main__' in Python

The problem comes from the know almost users to ask questions , then see the problem, I just did a simple answer. Later, I found that for many people, it is more accurate to say that most Python beginners do not have a deep understanding of this problem. So here I will make a summary and try to clarify this issue.

Program entry

For many programming languages, the program must have an entry point, such as C, C++, and fully object-oriented programming languages ​​Java, C#, etc. If you have been exposed to these languages, you should have a good understanding of the concept of program entry. Both C and C++ need to have a main function as the entry of the program, that is, the running of the program will start from the main function. Similarly, Java and C# must have a main class containing a Main method as the program entry.

But Python is different. It belongs to a scripting language. Unlike a compiled language, the program is compiled into a binary and then run. Instead, it dynamically interprets and runs line by line. That is, it runs from the first line of the script, and there is no unified entry point.

In addition to being directly run, a Python source code file can also be imported as a module (that is, a library). Whether it is imported or run directly, the topmost code will be run (Python uses indentation to distinguish code levels). In fact, when importing, there is a part of the code that we do not want to be executed.

To give an example to illustrate, suppose we have a file with the following content:

PI = 3.14

def main():
	print 'PI:', PI


We defined some constants in this file, and then wrote a main function to output the defined constants. Finally, running the main function is equivalent to doing a manual inspection of the definition to see if the values ​​are set correctly. Then we directly execute the file (python and output:

PI: 3.14

Now, we have an file to calculate the area of ​​a circle. The PI variable in the file needs to be used in this file. Then we import the PI variable from to

from const import PI

def calc_round_area(radius):
    return PI * (radius ** 2)

def main():
    print "round area: ", calc_round_area(2)


Run, output result:

PI: 3.14
round area:  12.56

As you can see, the main function in const is also run. In fact, we don't want it to be run. Main is provided only to test the constant definition. At this time, if __name__ == '__main__'it came in handy. Change a bit:

PI = 3.14

def main():
    print "PI:", PI

if __name__ == "__main__":

Then run, the output is as follows:

round area:  12.56

Then run, the output is as follows:

PI: 3.14

This is the effect we want.

if __name__ == '__main__'It is equivalent to the program entry of Python simulation . Python itself does not stipulate such writing, it is just a coding habit. Due to mutual references between modules, different modules may have such definitions, but there can only be one entry program. In the end which entry program is selected, depending on the __name__value.


__name__It is a built-in variable that is used to represent the name of the current module and also reflect the structure of a package. To give an example, suppose there is a package as follows:

├── b
│   ├──
│   └──

The contents of all py files in the directory are:

print __name__

We execute python -c "import a.b.c"and output the result:


It __name__can be seen that the level of a module in the package can be clearly reflected. In fact, the so-called module name is the name that needs to be used when importing, for example:

import tornado
import tornado.web

Here tornado and tornado.web are called the module name of the module.

If a module is executed directly, it is no packet structure, which __name__is __main__. For example, in the above example, we directly run the file (python a/b/, and the output results are as follows:


Therefore, if __name__ == '__main__'our simple understanding is: if the module is run directly, the code block is run, if the module is imported, the code block is not run .

In fact, this problem can also be derived from some other knowledge, such as __main__.pyfiles and Python's -mparameters.

Guess you like