"Reprint" Python in the If __name__ = = ' __main__ ' How to understand

Source: Internet
Author: User
Tags constant definition

Turn from the blue of the http://blog.konghy.cn/2017/04/24/python-entry-program/program entrance

For many programming languages, the program must have a portal, such as c,c++, and a fully object-oriented programming language java,c#. If you have been exposed to these languages, the concept of program entry should be well understood, C and C + + need to have a main function as the entrance to the program, that is, the operation of the program will start from the main function. Similarly, Java and C # must have a main class that contains the main method as a program entry.

Python, for its part, is a scripting language that does not compile the program into binary and run it as a compiled language, but instead runs on a dynamic line-by-row interpretation. That is, from the first line of the script to run, there is no unified portal.

A Python source file can also be imported as a module (that is, a library) in addition to being directly run. The topmost code is run, whether it's imported or run directly (Python uses indentation to differentiate the code hierarchy). In fact, in the import, there is a part of the code we do not want to be run.

For example, let's say we have a const.py file with the following:

PI = 3.14def main(): print "PI:", PImain()

We define some constants in this file, and then write a main function to output the defined constants, and finally run the main function as a manual check of the definition to see if the value is set to the right. Then we directly execute the file (Python const.py), output:

PI: 3.14

Now that we have a area.py file that calculates the area of the circle, which needs to use the PI variable in the const.py file, we import the PI variable from the const.py into the area.py:

from const import PIdef 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.14round area:  12.56

As you can see, the main function in Const is also run, in fact we do not want it to be run, provide main also just to test the constant definition. At this point, it came in if __name__ == ‘__main__‘ handy. Change the const.py:

PI = 3.14def main(): print "PI:", PIif __name__ == "__main__": main()

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

round area:  12.56

Then run the next const.py, the output is as follows:

PI: 3.14

That's the effect we want.

if __name__ == ‘__main__‘is equivalent to a Python simulation of the program entry . Python itself does not stipulate this, it is just a coding habit. Because of the mutual reference between modules, different modules may have such a definition, and the entry program can only have one. Exactly which entry program is selected, depending on __name__ the value.

__name__

__name__is a built-in variable that represents the name of the current module and also reflects the structure of a package. For example, suppose you have one of the following packages:

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

The contents of all the py files in the directory are:

print __name__

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

aa.ba.b.c

This shows that the __name__ level of a module in the package can be clearly reflected. In fact, the so-called module name is the import need to use the name, for example:

import tornadoimport tornado.web

The tornado and Tornado.web here are called module names for modules.

If a module is run directly, it has no package structure and its __name__ value is __main__ . For example, in the example above, we ran the c.py file (Python a/b/c.py) directly, and the output was as follows:

__main__

So, if __name__ == ‘__main__‘ our simple understanding is that if the module is run directly, then the code block is run and if the module is imported, the code block is not run .

In fact, this problem can also derive some other knowledge points, such as __main__.py file and Python -m parameters.

__main__.py file with Python-m

The parameters of Python are -m used to run a module or package as a script, and the __main__.py file is equivalent to the "entry program" of a package.

First we need to look python xxx.py at python -m xxx.py the difference. The difference between the two ways to run a Python program is to run it directly and to run it as a module.

Let's start with a simple example, assuming there is a Python file run.py, which reads as follows:

import sysprint sys.path

We start with a direct run (Python run.py), and the output (in order to illustrate the problem, the output only captures important parts, the same as below):

[‘/home/huoty/aboutme/pythonstudy/main‘, ...]

Then run as a module (python-m run.py):

[‘‘, ...]/usr/bin/python: No module named run.py

Since the output only lists the key parts, it should be easy to see the difference between them. The direct run is to place the directory where the run.py file resides in the Sys.path attribute. Running as a module is the directory where you enter the command (that is, the current working path) into the Sys.path attribute. Running in a modular way there is a different place where there is an extra row No module named run.py of errors. When actually running as a module, Python executes the import for run.py once, so it print sys.path is executed successfully, and then Python tries to run the run.py module, but the module is not run.py in the path variable, so an error is made. And the right way to run it should be python -m run .

This example does not clearly explain the problem. Then we look at __main__.py the role.

Still look at the example first, like the next package:

package├── __init__.py└── __main__.py
    • __init__.py
import sysprint "__init__"print sys.path
    • __main__.py
import sysprint "__main__"print sys.path

With python -m package running results:

__init__[‘‘, ...]__main__[‘‘, ...]

With python package running results:

__main__[‘package‘, ...]

Then let's summarize:

    • 1, plus-m parameter will add the current working directory to Sys.path, and not overtime will add the script directory to Sys.path .
    • 2. When you add the-m parameter, Python imports the module or package before executing
    • 3, __main__.py file is a package or directory of the entry program. the python package __main__.py file is always executed, either with or with the python -m package runtime.
Post

I tried to use a lengthy speech to explain how to understand if __name__ == ‘__main__‘ the problem in Python, and I don't know if I have enough to describe it. Python is really simple and elegant, but there are a lot of questions that are not easy to understand, such as many advanced features, such as meta-classes, generator expressions, descriptors, co-routines, and so on. Python does not have too many places to prescribe how, many usages are just idioms, such as self and what is discussed in this article. These are used either to make the code look more elegant, or to have previous experience. There is no limit to the possibilities of using Python, and you can write a lot of neat and elegant code.

Resources
    • Http://www.tuicool.com/articles/jMzqYzF
    • Http://stackoverflow.com/questions/4042905/what-is-main-py

"Reprint" Python in the If __name__ = = ' __main__ ' How to understand

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.