The role of __name__ = ' __main__ ' in Python

Source: Internet
Author: User

There is a phrase that sums up the meaning of this code in a classic way:

"Make a script both importable and executable"

It means that the script module that you write can be imported into other modules, and the module can be executed by itself .

This sentence, may start to listen to not very understand. The following examples illustrate:

Write a module first:

?
12345 #module.py defmain():   print "we are in %s"%__name__ if __name__ ==‘__main__‘:   main()

This function defines a main function, and we execute the PY file to find that the result is to print out "We is in __main__", stating that the contents of our if statement are executed, calling main ():

But what if we import the module from another module and call the main () function once?

?
123 #anothermodle.py frommodule importmain main()

The result of its execution is: we is in module

However, "We is in __main__" is not shown, which means that the function under module __name__ = ' __main__ ' is not executed.

This allows the "module" file to be run or introduced by other modules without executing the function 2 times. That's the point.

To summarize:

If we are directly executing a. py file, the file then "__name__ = = ' __main__ '" is true, but if we import the file through import from another. py file, then __name__ The value is the name of our py file, not the __main__.

This feature also has a use: When debugging code, in "if __name__ = = ' __main__ '" to add some of our debugging code, we can let the external module calls do not execute our debugging code, but if we want to troubleshoot the problem, directly execute the module file, Debug your code to work!

The role of __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.