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

Source: Internet
Author: User
Tags constant definition one more line

Summary

Popular understanding __name__ = = '__main__' : If you call Syed Py, in the eyes of friends, you are Syed ( __name__ == ‘李凯‘ ) ; in your own eyes, you are yourself. ( __name__ == ‘__main__‘ ).

If __name__ = = '__main__' means: when the. py file is run directly, the if The code block under __name__ = = '__main__' will be run, and when the. py file is imported as a module, the if The code block under __name__ = = '__main__' is not run.

Program entry

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 Import PI def Calc_round_area (RADIUS):     return PI * (RADIUS * * 2)def  Main ()    :print"", 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, if __name__ = = '__main__' comes in handy. Change the const.py:

Pi = 3.14def  Main ():    print"pi:", Pi if __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. Which entry is selected, depending on The value of the __name__.

__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____init__. py

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

Print __name__

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

Aa.ba.b.c

Thus, __name__ can clearly reflect the level of a module in the package. In fact, the so-called module name is the import need to use the name, for example:

Import Tornado Import 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: If the module is run directly, 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 the __main__. py file with the- m parameter of Python.

__main__.py file with Python-m

The- m parameter of Python is used to run a module or package as a script, while the __main__. py file is equivalent to a package's "entry program".

First we need to look at The difference between Python xxx.py and python-m xxx.py . 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 SYS Print 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

Because the output lists only the key parts, it should be easy to see the difference between them. The direct run is to put   run.py   files in the same directory as the   Sys.path   properties. Running as a module is the directory where you enter the command (that is, the current working path) into the   property. Run as a module there is a different place, one more line   No module named run.py  , so print sys.path   was executed successfully, then Python tried to run   run.py module, but there was no   run.py this module, so error. and the correct mode of operation should be   python-m run  .

This example does not clearly explain the problem. Then let's look at the role of __main__. py .

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

__init____main__. py
    • __init__.py
Import SYS Print " __init__ " Print Sys.path
    • __main__.py
Import SYS Print " __main__ " Print Sys.path

Run results with PYTHON-M package:

__init__ [', ...] __main__ [', ...]

Run the results with the python package :

__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 entry program. whether you're running with a python package or a python-m package , __main__.py files are always executed.
Post

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.

(go) How to understand if __name__ = = ' __main__ ' in Python

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.