Why does Python have a pass statement?

> This article is from the "Why Python" series, please see all articles

Regarding the statements in Python pass, it seems to be very simple (only 4 letters), and even beginners without any programming experience can grasp its usage very quickly.

The introduction of the official documentation is very simple, the following three examples can let us quickly understand how to use it:

Simply put, pass is a null operation. When the interpreter reaches it, it skips without doing anything other than checking whether the syntax is legal.

Compared with non-null operations such as return, break, continue and yield, the biggest difference is that it does not change the execution order of the program. It's like a comment we write, except it takes up a single line of code and doesn't have any effect on the scope it's in.

However, if you have a foundation in other languages, you might be wondering: why does Python have such a unique pass statement while other languages ​​don't?

Why is Python designed this way?

Is it to solve a common problem that most programming languages ​​face, or because it has its own new discoveries, so it creates a new feature?

In other words: Why does Python have a pass statement, what problems does it solve (benefit), and what problems can it cause without it (disadvantage)?

Next, this paper will analyze from two dimensions.

1. To people: as a space placeholder

I regard it as a concise way of commenting, which is equivalent to saying " reserve the space here first, and then fill in the specific code implementation later ".

For example, in the multi-layer if-elif-else structure, we can write the judgment condition first, then write the pass in the corresponding block, and then gradually improve it later.

For example, in the example given above, we can first write the class/function name and its input parameters, then skip (pass) the main code, and then fill it in slowly.

Pass is simple to write, and because it is a keyword, the IDE will give a prominent color distinction, so it is more convenient than writing comments.

As a space placeholder, pass can mainly facilitate us to conceive the local code structure, and has a certain auxiliary reminder effect.

However, as a way of commenting, it's too thin to write "# todo: xxxx", which is also colored by the IDE and has a more defined meaning. While simple to write, it also introduces a seemingly redundant keyword pass.

So, from the perspective of space placeholders, the pass is not a necessary design element in a programming language.

With it, we can express the semantics of "there is something here, but skip it for now", but without it, the content of the comment can be used instead.

2. To the machine: for grammatical integrity

For the usage of the previous item, the position of the pass in the code is theoretically unlimited.

However, when we use pass most often, it is basically on the next line of the colon, and this is the only statement in the code block indented at that level. (See the 3 examples above. For convenience, we only take an empty function as an example)

We can imagine what would happen if we didn't write it?

The answer is to report an indentation error:IndentationError: expected an indented block

# 将函数体的 pass 去除,会报错
def func():

func()

Because Python uses indentation to divide code blocks (for the reason, see Why does Python use indentation to divide code blocks? ), and the colon marks the appearance of a new indented code block, so this example will report a missing indented code block .

If we replace it with the annotations mentioned above, let's see what happens?

# 将函数体的 pass 换成注释
def func():
    # todo:此处有东西,以后补上
func()

Writing like this will also report an error:IndentationError: expected an indented block

The reason is that a comment is not valid syntactic content, it is ignored by the Python interpreter (ignore), unlike the pass statement which is "valid syntactic content, but skipped".

That is, indented code blocks must contain syntactically meaningful content. The following examples are valid:

def func():
    """这是一个字符串"""

def func2():
    123456

When Python defines a function, it must include the function body, that is, it contains both the declaration and the definition semantics. It cannot be written like some languages ​​can only use the declared semantics void test();.

However, since Python doesn't use curly braces, it can't define empty functions directly like some languages, i.e. write them void test(){}.

Based on the above analysis, when Python defines an empty function, it must have a legal function body, so it designs a pass statement that represents an empty operation. It is for completeness of syntax, and along with the colon, is equivalent to an empty pair of curly braces in other languages.

From the dimension of grammatical integrity, it is a necessary design element, if not, it must be replaced with a similar empty statement or special symbol.

On the human side, pass can mean "temporarily skipped", as a temporary placeholder, which will eventually be replaced by the actual code implementation; on the machine side, it can mean "skip directly", just to make up Syntax logic, and will not be replaced by other code.

Other languages ​​do not have a special statement or symbol to represent such placeholders (that is, the semantics are lacking), but they also do not need to bother to design a keyword to complete the syntax integrity (that is, the syntax is complete).

Back to the question at the beginning of this article: Why does Python have a pass statement, what problems can it solve (benefit), and what problems can it cause (disadvantage) without it?

Python uses the pass statement to support pure no-op code blocks (empty functions, empty classes, empty loop control blocks, etc.), and with it, it can additionally express a kind of placeholder semantics.

The former is for machines and must have, which is equivalent to the role of empty curly braces in other languages; the latter is for humans, not necessary, and can be expressed with comments, but because Python designed this statement, This usage is sometimes quite convenient.

If you think this article is a good analysis, then you should like these articles:

1. Why does Python use indentation to divide code blocks?

2. Is Python's indentation an anti-human design?

3. Why does Python not use a semicolon as a statement terminator?

4. Why does Python not have a main function? Why do I not recommend writing the main function?

5. Why does Python recommend snake-like nomenclature?

6. Why does Python not support the i++ auto-increment syntax and the ++ operator?

7. Why does Python only need one statement "a,b=b,a" to directly exchange two variables?

This article belongs to the "Why Python" series (produced by Python Cat), which mainly focuses on topics such as Python's syntax, design, and development. It tries to show the charming charm of Python by starting with "why" questions. All articles will be archived on Github, project address: https://github.com/chinesehuazhou/python-whydo

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

Guess you like

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