Why doesn't Python have a main function? Why do I not recommend writing the main function?

There is no doubt that there is no so-called main entry function in Python, but some articles on the Internet often mention "Python's main function", "It is recommended to write the main function"...

Some people are aware that his intention may be to imitate those authentic main functions, but many others are obviously misled (or misunderstood) and write very cumbersome code.

In this issue of "Why Python", let's talk about why Python doesn't have a main function?

Before starting the main topic, let's answer these two questions: What does the so-called "main function" mean? Why do some programming languages ​​force a main function to be written?

Some programming languages ​​use the main function as the execution entry point of the program, such as C/C++, C#, Java, Go and Rust, etc. They have specific meanings:

  • The main function name is mandatory, that is, there must be a main function
  • There can only be one main function at most, which means that the entry of the program is unique
  • The syntax format has certain requirements and has a relatively fixed template

Why force a main entry function?

These languages ​​are compiled languages, and the code needs to be compiled into executable binary files. In order for the operating system/launcher to find the starting point of the program, this function must be agreed upon. Simply put, in a lot of code, you need to define a significant start that can be used for execution.

It is not difficult to see that the main function is an important and integral part of those languages.

However, when we look at Python again, the situation is quite different.

  • Python is an interpreted language, that is, a scripting language. The running process is run from top to bottom, line by line, which means that its starting point is known.
  • Each .py file is an executable file, which can be used as the entry file of the entire program, that is to say, the entry of the program is flexible and variable, and there are no conventions that must be followed
  • Sometimes when running a Python project without specifying an entry file (common on the command line, such as "python -m http.server 8000"), it may be an existing __main__.pyfile , and the package it is in is executed as a "file"

In short, it means that Python, a scripting language, is different from a compiled language. It can choose a flexible execution method whether it is at the level of a single module (ie, a .py file) or at the level of a package composed of multiple modules. , unlike other languages ​​that cannot be executed without the agreed-upon entry.

That is to say, there is no need for Python to stipulate at the syntax level that programmers must define a uniform entry (whether it is a function or a class or something).

Some students may have doubts, because they often see or write the following code:

# main 里是某些主体代码
def main():
    …… 
 
if __name__ == '__main__':
    main()

Isn't this the main function of Python? I believe that many students will think so!

Not too! Not too!

Except that the function name is "main", it has nothing to do with the orthodox main function we introduced earlier, neither mandatory nor necessary to determine the execution order of the program. Without it, it doesn't cause any syntax problems.

The reason why some insiders want to name a "main" function is actually to emphasize its "main" status and to artificially arrange it as the first function to execute. They may think that functions named this way are easier to remember.

The reason why some insiders want to write if __name__ == '__main__', may want to indicate that main() only runs when the current script is directly executed, and does not want to be run when other modules are imported.

For these "insiders", they have some truth.

However, I personally do not recommend this way of writing, and even sometimes feel very disgusted!

The most obvious example: there are only dozens of lines of code, or there is only one script file to implement a simple function (a small crawler, draw a picture with turtle, etc.), but they are all written in the previous style.

I feel sick every time I see this kind of unthinkingly cumbersome code. Why write that line of if statement? If possible, the main function should be split, not even encapsulated into a function!

My personal experience is as follows:

  • Break the inertial thinking and write authentic code. The main entry function is unique to some languages. It should not be used in Python. It should understand the characteristics of scripting languages ​​and write in a concise and elegant style.
  • Use main.py instead of main(). Because the program execution unit of Python is actually a script file, not a function or class, it is recommended to name the entry file main.py, and the internal functions are determined according to requirements.
  • If possible, use it __main__.pyas the entry file. This file is used in conjunction with the "-m" parameter of the command line, which is very useful. Recommended reading: Typical usage, principle analysis and evolution of -m in Python
  • Writing is not recommended if __name__ == '__main__'. First of all, if there is only one file, it is not recommended to write because there is no possibility of exporting. Secondly, when there are multiple files, it is highly not recommended to write this sentence in the entry file (main.py). The code logic of this file should be refined. In theory, its content should not be exported to other modules for use, because it is the starting point! Finally, it is not recommended to write multi-file non-entry files, because the biggest effect of writing this judgment in non-entry files is to write some test code, but the test code should be separated and written to a special directory or file.

Summary: This article first explains what the main entry function is, and why some languages ​​force the main function to be written; then, it explains why Python does not need to write the main function; finally, it is aimed at some people's inertial misunderstandings, sharing My personal four-point programming experience.

This article belongs to the "Why Python" series of articles (produced by Python Cat), which mainly focuses on topics such as Python's syntax, design, and development, and tries to show the charming charm of Python by starting with "why" questions. Some topics will have a video version, please watch at station B, watch address: video address

The public number [ Python Cat ], this number serializes a series of high-quality articles, including why Python series, Cat Philosophy series, Python advanced series, good book recommendation series, technical writing, high-quality English recommendation and translation, etc. Welcome to pay attention .

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324029844&siteId=291194637
Recommended