Home >Backend Development >Python Tutorial >Do you know why Python has a pass statement?

Do you know why Python has a pass statement?

coldplay.xixi
coldplay.xixiforward
2020-10-30 16:54:062462browse

Python Video Tutorial column introduces why Python needs a pass statement.

Do you know why Python has a pass statement?

Regarding the pass statement in Python, it seems simple (only 4 letters), even a beginner without any programming experience can Learn how to use it quickly.

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

Do you know why Python has a pass statement?

To put it simply, pass is a null operation. When the interpreter executes it, it does nothing except check whether the syntax is legal and skips it.

Compared with non-empty operations such as return, break, continue and yield, the biggest difference is that it does not change the execution order of the program. It is like a comment we write, except that it occupies a line of code and does not have any impact on the scope in which it is located.

However, if you have a foundation in other languages, you may be curious: Why does Python have such a unique pass statement, but other languages ​​do not?

Why is Python designed like this?

Is it to solve the common problems faced by most programming languages, or is it a new feature created because it has its own new discoveries?

In other words: Why does Python have the pass statement, what problems does it solve (benefits), and what problems (disadvantages) will it cause without it?

Next, this article will analyze from two dimensions.

1. To people: As a space placeholder

I regard it as a concise and comprehensive way of commenting, which is equivalent to saying "Reserve a place here first, and then come back later" Fill in the specific code to implement ".

For example, in a multi-layered if-elif-else structure, we can write the judgment conditions first, then write pass in the corresponding block, and then slowly 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 later.

pass is easy to write, and because it is a keyword, the IDE will give you conspicuous color distinctions, so it is more convenient than writing comments.

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

However, as a way of commenting, it is too thin and inferior to writing "# todo: xxxx". The latter will also be highlighted in color by the IDE and has a clearer meaning. Although simple to write, it also introduces a seemingly redundant keyword pass.

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

With it, we can express the semantics of "there is something here, but skip it for now", but without it, it can be replaced by annotation content.

2. For the machine: For the sake of grammatical integrity

For the usage of the previous item, the position where pass appears in the code is theoretically unrestricted.

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

We can imagine what would happen if we did not write it?

The answer is that an indentation error will be reported: IndentationError: expected an indented block

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

Because Python uses indentation to divide code blocks (for the reason, please refer to "Why 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.

What if we use the comments mentioned above instead?

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

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

The reason is that the comment is not a valid grammatical content and will be ignored by the Python interpreter ( ignore), unlike the pass statement which is "valid syntax content, but skipped".

In other words, the indented code block must contain grammatically meaningful content. The following examples are valid:

def func():
    """这是一个字符串"""def func2():
    123456复制代码

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

However, since Python does not use curly braces, it cannot directly define an empty function like some languages, which is written as void test(){}.

Based on the above analysis, Python must have a legal function body when defining an empty function, so a pass statement is designed to represent a no-op. It is intended to complete the syntax and, along with the colon, is equivalent to an empty pair of braces in other languages.

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

For humans, pass can mean "temporarily skip". As a temporary placeholder, it will eventually be replaced by the actual code implementation; for machines, it can mean "skip directly." ” is only used to complete the grammatical logic and will not be replaced by other codes.

Other languages ​​do not have a special statement or symbol to represent this kind of placeholder (that is, the semantics are lacking), but they do not need to bother to design a keyword to complete the grammatical integrity ( i.e. grammatically complete).

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

Python uses the pass statement to support purely no-operation code blocks (empty functions, empty classes, empty loop control blocks, etc.). With it, additional expressions can be Come up with a placeholder semantics.

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

Related free learning recommendations: python video tutorial

The above is the detailed content of Do you know why Python has a pass statement?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete