Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why does Python only need one sentence a ~?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "why Python only needs a sentence", the content of the explanation in the article is simple and clear, easy to learn and understand, now please follow the editor's train of thought slowly in depth, together to study and learn "why Python only need a sentence a sentence" bar!

The most obvious example is multiple assignments, which assign values to multiple variables at the same time in a single statement:

> x, y = 1,2 > print (x, y) # result: 1 2

In this case, the two digits to the right of the assignment operator "=" are stored in a tuple, which becomes (1 ~ 2), then unpackaged and assigned to the two variables to the left of the "=" sign.

This can be confirmed if we directly write x = 1, 2, and then print out x, or write a tuple to the right of the "=" sign:

> x = 1,2 > > print (x) # result: (1,2) > > x, y = (1,2) > print (x, y) # result: 1 / 2

When introducing this feature, some blogs or official account articles usually give an example, that is, based on two variables, directly exchange their values:

> x, y = 1,2 > x, y = y, x > print (x, y) # result: 2 1

In general, the operation of exchanging two variables requires the introduction of a third variable. The reason is simple: if you want to exchange the water in two cups, you will naturally need a third container as a transit.

However, Python is written without the help of intermediate variables, it is in the same form as the previous unpacking assignment. Because of this similarity, many people mistakenly think that Python's variable exchange operation is also based on unpacking operation.

But is this really the case?

I searched and found that someone had tried to answer this question, but their answer was not comprehensive enough. (of course, there are many wrong answers, and many more people just know it, but never want to know why.)

Let's first put the answer to this article: Python's swap variable operation is not entirely based on unpacking operation, sometimes yes, sometimes not!

Do you think this answer is amazing? Is it unheard of?!

What's going on? First, let's take a look at the two simplest variables in the title. Let's take a look at the compiled bytecode on the dis killer:

There are two windows in the picture above to make it easy to compare the difference between "a journal" and "a journal 1, 2":

The "arecoverable LOAD_FAST a" operation: two STORE_FAST read references to variables from the local scope and store them on the stack, followed by the most critical ROT_TWO operation, which exchanges the reference values of the two variables, and then the two STORE_FAST writes the variables in the stack to the local scope.

Operation: the first step is LOAD_CONST to put the two numbers on the right side of the sign as tuples on the stack, the second step is to unpack the UNPACK_SEQUENCE sequentially, and then write the unpacking result to the variables in the local scope.

It is obvious that the two similar forms of writing actually do not perform the same operation. In the operation of swapping variables, there are no steps to pack and unpack!

The ROT_TWO instruction is a quick operation implemented by the CPython interpreter on the two elements at the top of the stack, changing the reference object they point to.

Two similar instructions are ROT_THREE and ROT_FOUR, which are quick swaps of three and four variables (excerpt from the ceval.c file, the latest 3.9 branch):

The predefined stack top operations are as follows:

Check the official documentation for explanations of these directives, where ROT_FOUR is a new addition to version 3.8:

ROT_TWO Swaps the two top-most stack items. ROT_THREE Lifts second and third stack item one position up, moves top down to position three. ROT_FOUR Lifts second, third and forth stack items one position up, moves top down to position four. New in version 3.8.

CPython should think that the exchange of these variables is common, so it provides special optimization instructions. Just like [- 5256] these small integers are pre-placed in the integer pool.

For the swap operation of more variables, the unpacking operation mentioned earlier will actually be used:

The BUILD_TUPLE instruction in the screenshot creates a tuple of a given number of stack top elements, which are then unpackaged by the UNPACK_SEQUENCE instruction and assigned in turn.

It is worth mentioning that the reason why there is one more build operation here than the previous "arecalogical 1pl 2" is that the LOAD_FAST of each variable needs to be put into a separate stack first and cannot be directly combined into a LOAD_CONST stack. In other words, when there is a variable to the right of the "=" sign, the LOAD_CONST tuple in the previous article will not occur.

One last detail worth mentioning is that the instructions are related to the number of elements in the stack, not to the number of variables actually exchanged in the assignment statement. Just look at an example:

At this point in the analysis, you should understand the conclusion in the previous article, right?

Let's sum up a little bit:

Python can implement multiple assignments in one statement, which makes use of the feature of sequence unpacking.

Python can exchange variables in one sentence without introducing intermediate variables. When the number of variables is less than 4 (less than 5 since version 3.8), CPython uses ROT_* instructions to exchange elements in the stack. When the number of variables exceeds, it uses the characteristics of sequence unpacking.

Sequence unpacking is a major feature of Python, but in the example in this article, the CPython interpreter also provides several optimized instructions in small operations, which is definitely beyond the perception of most people.

Thank you for your reading, the above is the content of "why Python only needs a sentence". After the study of this article, I believe you have a deeper understanding of why Python only needs a sentence, and the specific use still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report