Write Python scripts, be sure to add this

thumbnail

Author: Xianhuan

Python technology

People who use Python often write some scripts. Whether it is to improve work efficiency or to meet some specific needs, Python scripts are a common and useful thing.

However, I recently discovered a problem that I hadn’t noticed before, that is, whether to add if name == “main“: in the script, this statement actually has a great impact on the use of the script, and there is a lot of knowledge in it. .

Common Misunderstandings

Many friends are more casual when writing scripts. Simple scripts are directly written down, without functions, and executed sequentially. For more complex scripts, functions may be added. This way of writing is less readable, and often makes people unable to find the entry and order of program execution at a glance.

The recommended way of writing in the Python community is to add the following statement when writing a script:

def main():

do something

print(“do something.”)

if name == “main“:

main()

When most people see this, will they say, what is this, it is not so important to add this or not!

Don’t be too busy to be disdainful, let’s break it down carefully together!

What is the use

Before specifying the role of if name == ‘main’, let’s get a feel for it intuitively from a simple example.

const.py

PI = 3.14

def train():

print(“PI:“, PI)

train()

area.py

from const import PI

def calc_round_area(radius):

return PI * (radius ** 2)

def calculate():

print(“round area: “, calc_round_area(2))

calculate()

Let’s take a look at the running result of area.py:

PI: 3.14

round area: 12.56

The PI variable of , when running, the print in the function train() in const.py is also brought over, and we only refer to the variable, not the function, so we don’t want to see it.

The solution to this problem is also very simple, we only need to add a sentence to const.py:

PI = 3.14

def train():

print(“PI:“, PI)

if name == “main“:

train()

Run area.py again, the output is as follows:

round area: 12.56

This is our expected result.

Program running entry

From the above example, it can be found that if there is no if name==”main“: , all the code in const.py is executed when the file is imported as area.py, and only the imported part of the code is run after adding.

This is the obvious effect of if name==”main“:, in fact, if name==”main“: is equivalent to the program entry of Python simulation. Due to the mutual references between modules, different modules may have such definitions, and there can only be one entry program, which entry program is selected depends on the value of name.

Let’s look at another small program:

test.py

print(“look here”)

print(name)

if name == ‘main‘:

print(“I’m test.py”)

The result of running the program is as follows:

look here

main

I’m test.py

It can be found that the value of the variable name is main at this time, so “I’m test.py” is printed. If you run other files and call this file through the running file, the statement will not be printed, because the program entry is incorrect, the statement will not be executed.

code specification

With if name==”main“: equivalent to the Python program also has an entry function, we can clearly know where the logic of the program begins, of course, we also need to consciously put the start logic of the program here. In fact, this is what PyCharm recommends.

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

Great role in multi-process scenarios

If you use multiple processes to do parallel computing, 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)

Running this code, the console will keep printing:

processing in parallel

processing in parallel

processing in parallel

processing in parallel

processing in parallel

processing in parallel

processing in parallel

processing in parallel

processing in parallel

And the program will keep reporting RuntimeError.

If you add if name==”main“: , the program will work 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)

Python’s multi-program is to start multiple Python interpreters. Each Python interpreter will import your script and copy a copy of global variables and functions for subprocesses. If there is if name==”main“:, then The code behind it will not be imported and will not be executed repeatedly. Otherwise, the code that creates multiple processes will be imported and executed, thus creating subprocesses infinitely recursively.

Summarize

if name==”main“: Although not mandatory, I strongly recommend that you follow this specification when writing scripts. It is a convention of the Python community and corresponds to the Zen of Python: explicit is better than implicit.

Latest Programming News and Information | GeekBar

Related Posts