Role of _ name __= '_ main _' in python

Source: Internet
Author: User
This article mainly introduces _ name _ in python. Many new users often see _ name _ = \ '_ main __\' in python. code, many new users may be confused at the beginning. What is the role of _ name _ = '_ main _' in python?

Here is a classic summary of the significance of this Code:

"Make a script both importable and executable"

That isThe script module you write can be imported to other modules, and the module can be executed by itself..

This sentence may not be quite understandable at first. The following is an example:

Write a module first:

#module.pydef main():  print "we are in %s"%__name__if __name__ == '__main__':  main()

This function defines a main function. we execute this py file and find that the result is printed "we are in _ main _", it indicates that the content in our if statement is executed and main () is called ():

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

#anothermodle.pyfrom module import mainmain()

The execution result is: we are in module

However, the function "we are in _ main _" is not displayed, that is, the function under module _ name _ = '_ main _' is not executed.

In this way, the "module" file can be run, introduced by other modules, and the function is not executed twice. This is the key.

Summary:

If we directly execute. in The py file, "_ name _ = '_ main _'" is True,. when the py file is imported through import, the value of _ name _ is the name of the py file instead of _ main __.

This function is also useful: When debugging code, add some of our debugging code in "if _ name _ = '_ main, we can prevent external modules from executing our debugging code when calling the Code. However, if we want to troubleshoot the problem, we can directly execute the module File to run the debugging code normally!

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.