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 const.py file with the following content:

PI = 3.14

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

main()

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 const.py) and output:

PI: 3.14

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

from const import PI

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

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

main()

Run area.py, 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 const.py a bit:

PI = 3.14

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

if __name__ == "__main__":
    main()

Then run area.py, the output is as follows:

round area:  12.56

Then run const.py, 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__

__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:

a
├── b
│   ├── c.py
│   └── __init__.py
└── __init__.py

The contents of all py files in the directory are:

print __name__

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

a
a.b
a.b.c

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 c.py file (python a/b/c.py), and the output results are as follows:

__main__

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

Origin blog.csdn.net/xp178171640/article/details/115029917