I found that there are many friends write Python script is very casual, either don’t function or functions are defined, anyway, the first not to perform the first line of code is located in where, this script readability is poor, and easy to hide bugs, in addition, it is not a Python community recommended practice, the solution to this problem is very simple, When we write Python scripts, we must add this:

def main() :
    # do something
    print("do something.")


if __name__ == "__main__":
    main()
Copy the code

You may object: I write whatever I like, why should I listen to you, write if __name__… ?

Hold on, let me give you three reasons.

First, it makes it more explicit what Python files do

The value of __name__ is “main” when the script is directly executed by the Python interpreter, and “main” when the script is imported by other Python programs. The value of __name__ is the name of the Python script. Suppose we have some_script.py with the following contents:

print("some_script.py")
print(__name__)
Copy the code

Import the following in the Python interpreter:

❯ vim some_script.py
❯ python
Python 3.8. 5 (v38.. 5:580fbb018f, Jul 20 2020.12:11:27)
[Clang 6.0 (clang-600.057.)] on darwin
Type "help"."copyright"."credits" or "license" for more information.
>>> import some_script
some_script.py
some_script
>>>
Copy the code

As you can see, the __name__ value is the filename of the Python script some_script.

If __name__ == “__main__”: the following code will not run when importing.

Understand this point, if __name__ = = “__main__” : can be used as an indicator to distinguish the script and the library, when we see the if __name__ = = “__main__” : Explicit is better than implicit, isn’t it? Explicit is better than implicit. Explicit is Explicit.

Here’s another example:

If you write a script without if __name__ == “__main__”: called bad_script.py, it reads as follows:

def useful_function(x) :
    return x * x


class UsefulClass:
    def __init__(self, x) :
        self.x = x

Have you tested it for yourself? Nothing wrong with it
for i in range(7) :print(useful_function(i))
Copy the code

Someone else wrote a useful. Py reference to your useful_function:

from bad_script import useful_function


def main() :
    print(f'{useful_function(3) =}')


if __name__ == '__main__':
    main()
Copy the code

After running, unexpected content was found to be printed, as shown in red below:

Check the reason for a long time, found that is your script output, you say others will scold you?

Second, it makes Python files more readable and IDE friendly

If __name__ == “__main__”: Python programs also have an entry function, we can clearly know where the program logic starts (of course, we need to consciously put the program start logic here).

In fact, this is what PyCharm recommended. When you create a new project, it creates main.py that looks like this by default:

There is also a green run button at the far left of the if __name__ == “__main__”: line. Click on this line to start the program.

Why do many good programming languages such as C, Java, Golang, and C++ have a main entry function? I think a very important reason is that the program entrance is unified, easy to read.

Third, in multi-process scenarios, you must use if main

Let’s say you do parallel computing with multiple processes and write code like this:

import multiprocessing as mp


def useful_function(x) :
    return x * x

print("processing in parallel")
with mp.Pool() as p:
    results = p.map(useful_function, [1.2.3.4])
    print(results)

Copy the code

As you run it, you’ll notice that the program keeps creating processes and also keeps raising RuntimeErrors. You can’t stop the program even if you Ctrl/C. Adding if __name__ == “__main__”: the program will do as expected:

import multiprocessing as mp


def useful_function(x) :
    return x * x

if __name__ == '__main__':
    print("processing in parallel")
    with mp.Pool() as p:
        results = p.map(useful_function, [1.2.3.4])
        print(results)
Copy the code

Why is that?

If __name__ == “__main__”: if __name__ == “__main__”: The following code will not be imported and will not be executed repeatedly. Otherwise, the code for creating multiple processes will be imported, will be executed, and will recursively create child processes indefinitely. Python3 will tell you RuntimeError, the order of process creation and error, so you’ll keep creating processes, and you’ll keep getting errors, and Ctrl/C won’t stop, You can only kill the entire terminal. Here’s an official explanation

The last word

If __name__ == “__main__”: This is not mandatory, but I strongly recommend it for the above three reasons. It is a convention of the Python community that corresponds to the Python Zen: explicit is better than obscure. Just as the _ name is meant to tell the reader that the variable is not important and will not be used later. When you see Python scripts with if __name__ == “__main__”:, you realize that this is an executable script, and that this part of the code will not be executed when imported by other programs, as is required in multi-process programs.

If you have a harvest, welcome to like, follow, watch, thank you for reading.