Table of Contents
Control flow implementation
Home Backend Development Python Tutorial How to implement the control flow of Python virtual machine bytecode

How to implement the control flow of Python virtual machine bytecode

May 26, 2023 pm 12:13 PM
python

Control flow implementation

Control flow This part of the code mainly involves the following bytecode instructions. All the following bytecode instructions will have a parameter:

  • JUMP_FORWARD, the complete instruction will add this parameter to the position of the currently executing bytecode instruction, and then jump to the corresponding result to continue execution.

  • If the top element of the stack is true, the instruction to change the bytecode execution position to the received parameter value is "POP_JUMP_IF_TRUE". Pop the top element from the stack.

  • POP_JUMP_IF_FALSE, this instruction is the same as POP_JUMP_IF_TRUE, the only difference is to determine whether the top element of the stack is equal to true.

  • JUMP_IF_TRUE_OR_POP, if the top element of the stack is equal to true, the bytecode execution position is set to the value corresponding to the parameter, and there is no need to pop the top element of the stack. If the top element of the stack is false, the element must be popped.

  • JUMP_IF_FALSE_OR_POP is the same as JUMP_IF_TRUE_OR_POP but requires the top element of the stack to be equal to false.

  • JUMP_ABSOLUTE directly sets the execution position of the bytecode to the value of the parameter.

In general, these jump instructions allow the Python interpreter to change the execution flow according to specific conditions when executing bytecode, and implement basic language structures such as loops and conditional statements. .

Now we use an example to deeply understand the execution process of the various instructions above.

import dis
 
 
def test_control01():
    a = 1
 
    if a > 1:
        print("a > 1")
    elif a < 1:
        print("a < 1")
    else:
        print("a == 1")
 
if __name__ == &#39;__main__&#39;:
    dis.dis(test_control01)
Copy after login

The output result of the above program is as follows:

6         0 LOAD_CONST             1 (1)
          2 STORE_FAST                            
                       4 LOAD_FAST 3 22

9 12 LOAD_GLOBAL 0 (print)
14 LOAD_CONST 2 (' a > 1')
          16 CALL_FUNCTION         1
          18 POP_TOP
        20 JUMP_FORWARD         26 (to 48)

10 >> 22 LOAD_FAST 0 (a)
24 LOAD_CONST 1 (1)
26 Compare_op 0 (& LT;) ## 28 POP_JUMP_IF_FALSE 40
11 30 LOAD_GLOBAL 0 (Print)
32 load_const 3 ('a & lt; 1')#34 CALL_FUNCTION 1
36 POP_TOP
38 JUMP_FORWARD 8 (to 48)

13 >> 40 LOAD_GLOBAL                               
                                                                                                                                                                                                                     #           44 CALL_FUNCTION         1
            46 POP_TOP
                    48 LOAD_CONST                 0 (None)
                   RETURN_VALUE


Let’s simulate the above bytecode execution process now. Use counter to indicate the execution position of the current bytecode:

Before the bytecode starts executing, the status of the stack space and counter is as follows:


Now execute the first bytecode LOAD_CONST. After execution, counter = 2. Because this bytecode occupies one byte and the parameter stack is one byte, the position of the bytecode executed next time is in the bytecode. Three lower positions, the corresponding subscript is 2, so counter = 2.

How to implement the control flow of Python virtual machine bytecode

Now execute the second bytecode STORE_FAST, let a point to 1, the same STORE_FAST opcode and operand each occupy one byte, so this word is executed There is no data in the stack space after the section code, counter = 4.

How to implement the control flow of Python virtual machine bytecode

Next, LOAD_FAST loads the object pointed to by a, which is 1, into the stack. At this time, counter = 6, and LOAD_CONST loads the constant 1 into the stack space. This When counter = 8, after executing these two instructions, the stack space changes as shown below:

How to implement the control flow of Python virtual machine bytecode

The next instruction is COMPARE_OP, this instruction has a The parameter represents the symbol of comparison. Here it is comparing a > 1, and the comparison result will be pushed into the stack. The comparison result is false, because COMPARE_OP will first pop up the two inputs of the stack space, so after executing this The values ​​of the stack space and counter after the instruction are as follows:

How to implement the control flow of Python virtual machine bytecode

The following instruction is POP_JUMP_IF_FALSE. According to the meaning of the previous bytecode, this bytecode will pop the false on the top of the stack. , and will jump, and program the value of counter directly to the value of the parameter. Here his parameter is 22, so counter = 22. After executing this instruction, the result is as follows:

How to implement the control flow of Python virtual machine bytecode

Because it has jumped to 22, the next instruction to be executed is LOAD_FAST, which loads the variable a into the stack space. LOAD_CONST loads the constant 1 into the stack space. After these two executions, the changes The situation is as follows:

How to implement the control flow of Python virtual machine bytecode

Execute POP_JUMP_IF_FALSE this time, and the result this time is also false, so continue to execute POP_JUMP_IF_FALSE, this time the parameter is 40, directly set the value of counter to 40 .

How to implement the control flow of Python virtual machine bytecode

Next, LOAD_GLOBAL loads a global variable print function counter and becomes 42, LOAD_CONST loads the string "a == 1" into the stack space, counter = 44, and the status is As follows:

How to implement the control flow of Python virtual machine bytecode

CALL_FUNCTION This bytecode has one parameter, indicating the number of parameters for calling the function. Here it is 1, because the print function has only one parameter and then outputs a string. "a== 1", but what needs to be noted here is that the print function will return None, so the status after executing CALL_FUNCTION is as follows:

How to implement the control flow of Python virtual machine bytecode

At this point, the above function is almost executed. That’s it. The next few bytecodes are very simple, so I won’t describe them again.

The above is the detailed content of How to implement the control flow of Python virtual machine bytecode. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles