查询字节码指令集:
1 >>> import opcode 2 >>> for op in range(len(opcode.opname)): 3 print('ox%.2X(%.3d): %s' % (op, op, opcode.opname[op])) 4 5 6 ox00(000): <0> 7 ox01(001): POP_TOP 8 ox02(002): ROT_TWO 9 ox03(003): ROT_THREE 10 ox04(004): DUP_TOP 11 ox05(005): DUP_TOP_TWO 12 ox06(006): <6> 13 ox07(007): <7> 14 ox08(008): <8> 15 ox09(009): NOP 16 ox0A(010): UNARY_POSITIVE 17 ox0B(011): UNARY_NEGATIVE 18 ox0C(012): UNARY_NOT 19 ox0D(013): <13> 20 ox0E(014): <14> 21 ox0F(015): UNARY_INVERT 22 ox10(016): <16> 23 ox11(017): <17> 24 ox12(018): <18> 25 ox13(019): BINARY_POWER 26 ox14(020): BINARY_MULTIPLY 27 ox15(021): <21> 28 ox16(022): BINARY_MODULO 29 ox17(023): BINARY_ADD 30 ox18(024): BINARY_SUBTRACT 31 ox19(025): BINARY_SUBSCR 32 ox1A(026): BINARY_FLOOR_DIVIDE 33 ox1B(027): BINARY_TRUE_DIVIDE 34 ox1C(028): INPLACE_FLOOR_DIVIDE 35 ox1D(029): INPLACE_TRUE_DIVIDE 36 ox1E(030): <30> 37 ox1F(031): <31> 38 ox20(032): <32> 39 ox21(033): <33> 40 ox22(034): <34> 41 ox23(035): <35> 42 ox24(036): <36> 43 ox25(037): <37> 44 ox26(038): <38> 45 ox27(039): <39> 46 ox28(040): <40> 47 ox29(041): <41> 48 ox2A(042): <42> 49 ox2B(043): <43> 50 ox2C(044): <44> 51 ox2D(045): <45> 52 ox2E(046): <46> 53 ox2F(047): <47> 54 ox30(048): <48> 55 ox31(049): <49> 56 ox32(050): <50> 57 ox33(051): <51> 58 ox34(052): <52> 59 ox35(053): <53> 60 ox36(054): STORE_MAP 61 ox37(055): INPLACE_ADD 62 ox38(056): INPLACE_SUBTRACT 63 ox39(057): INPLACE_MULTIPLY 64 ox3A(058): <58> 65 ox3B(059): INPLACE_MODULO 66 ox3C(060): STORE_SUBSCR 67 ox3D(061): DELETE_SUBSCR 68 ox3E(062): BINARY_LSHIFT 69 ox3F(063): BINARY_RSHIFT 70 ox40(064): BINARY_AND 71 ox41(065): BINARY_XOR 72 ox42(066): BINARY_OR 73 ox43(067): INPLACE_POWER 74 ox44(068): GET_ITER 75 ox45(069): STORE_LOCALS 76 ox46(070): PRINT_EXPR 77 ox47(071): LOAD_BUILD_CLASS 78 ox48(072): YIELD_FROM 79 ox49(073): <73> 80 ox4A(074): <74> 81 ox4B(075): INPLACE_LSHIFT 82 ox4C(076): INPLACE_RSHIFT 83 ox4D(077): INPLACE_AND 84 ox4E(078): INPLACE_XOR 85 ox4F(079): INPLACE_OR 86 ox50(080): BREAK_LOOP 87 ox51(081): WITH_CLEANUP 88 ox52(082): <82> 89 ox53(083): RETURN_VALUE 90 ox54(084): IMPORT_STAR 91 ox55(085): <85> 92 ox56(086): YIELD_VALUE 93 ox57(087): POP_BLOCK 94 ox58(088): END_FINALLY 95 ox59(089): POP_EXCEPT 96 ox5A(090): STORE_NAME 97 ox5B(091): DELETE_NAME 98 ox5C(092): UNPACK_SEQUENCE 99 ox5D(093): FOR_ITER 100 ox5E(094): UNPACK_EX 101 ox5F(095): STORE_ATTR 102 ox60(096): DELETE_ATTR 103 ox61(097): STORE_GLOBAL 104 ox62(098): DELETE_GLOBAL 105 ox63(099): <99> 106 ox64(100): LOAD_CONST 107 ox65(101): LOAD_NAME 108 ox66(102): BUILD_TUPLE 109 ox67(103): BUILD_LIST 110 ox68(104): BUILD_SET 111 ox69(105): BUILD_MAP 112 ox6A(106): LOAD_ATTR 113 ox6B(107): COMPARE_OP 114 ox6C(108): IMPORT_NAME 115 ox6D(109): IMPORT_FROM 116 ox6E(110): JUMP_FORWARD 117 ox6F(111): JUMP_IF_FALSE_OR_POP 118 ox70(112): JUMP_IF_TRUE_OR_POP 119 ox71(113): JUMP_ABSOLUTE 120 ox72(114): POP_JUMP_IF_FALSE 121 ox73(115): POP_JUMP_IF_TRUE 122 ox74(116): LOAD_GLOBAL 123 ox75(117): <117> 124 ox76(118): <118> 125 ox77(119): CONTINUE_LOOP 126 ox78(120): SETUP_LOOP 127 ox79(121): SETUP_EXCEPT 128 ox7A(122): SETUP_FINALLY 129 ox7B(123): <123> 130 ox7C(124): LOAD_FAST 131 ox7D(125): STORE_FAST 132 ox7E(126): DELETE_FAST 133 ox7F(127): <127> 134 ox80(128): <128> 135 ox81(129): <129> 136 ox82(130): RAISE_VARARGS 137 ox83(131): CALL_FUNCTION 138 ox84(132): MAKE_FUNCTION 139 ox85(133): BUILD_SLICE 140 ox86(134): MAKE_CLOSURE 141 ox87(135): LOAD_CLOSURE 142 ox88(136): LOAD_DEREF 143 ox89(137): STORE_DEREF 144 ox8A(138): DELETE_DEREF 145 ox8B(139): <139> 146 ox8C(140): CALL_FUNCTION_VAR 147 ox8D(141): CALL_FUNCTION_KW 148 ox8E(142): CALL_FUNCTION_VAR_KW 149 ox8F(143): SETUP_WITH 150 ox90(144): EXTENDED_ARG 151 ox91(145): LIST_APPEND 152 ox92(146): SET_ADD 153 ox93(147): MAP_ADD 154 ox94(148): <148> 155 ox95(149): <149> 156 ox96(150): <150> 157 ox97(151): <151> 158 ox98(152): <152> 159 ox99(153): <153> 160 ox9A(154): <154> 161 ox9B(155): <155> 162 ox9C(156): <156> 163 ox9D(157): <157> 164 ox9E(158): <158> 165 ox9F(159): <159> 166 oxA0(160): <160> 167 oxA1(161): <161> 168 oxA2(162): <162> 169 oxA3(163): <163> 170 oxA4(164): <164> 171 oxA5(165): <165> 172 oxA6(166): <166> 173 oxA7(167): <167> 174 oxA8(168): <168> 175 oxA9(169): <169> 176 oxAA(170): <170> 177 oxAB(171): <171> 178 oxAC(172): <172> 179 oxAD(173): <173> 180 oxAE(174): <174> 181 oxAF(175): <175> 182 oxB0(176): <176> 183 oxB1(177): <177> 184 oxB2(178): <178> 185 oxB3(179): <179> 186 oxB4(180): <180> 187 oxB5(181): <181> 188 oxB6(182): <182> 189 oxB7(183): <183> 190 oxB8(184): <184> 191 oxB9(185): <185> 192 oxBA(186): <186> 193 oxBB(187): <187> 194 oxBC(188): <188> 195 oxBD(189): <189> 196 oxBE(190): <190> 197 oxBF(191): <191> 198 oxC0(192): <192> 199 oxC1(193): <193> 200 oxC2(194): <194> 201 oxC3(195): <195> 202 oxC4(196): <196> 203 oxC5(197): <197> 204 oxC6(198): <198> 205 oxC7(199): <199> 206 oxC8(200): <200> 207 oxC9(201): <201> 208 oxCA(202): <202> 209 oxCB(203): <203> 210 oxCC(204): <204> 211 oxCD(205): <205> 212 oxCE(206): <206> 213 oxCF(207): <207> 214 oxD0(208): <208> 215 oxD1(209): <209> 216 oxD2(210): <210> 217 oxD3(211): <211> 218 oxD4(212): <212> 219 oxD5(213): <213> 220 oxD6(214): <214> 221 oxD7(215): <215> 222 oxD8(216): <216> 223 oxD9(217): <217> 224 oxDA(218): <218> 225 oxDB(219): <219> 226 oxDC(220): <220> 227 oxDD(221): <221> 228 oxDE(222): <222> 229 oxDF(223): <223> 230 oxE0(224): <224> 231 oxE1(225): <225> 232 oxE2(226): <226> 233 oxE3(227): <227> 234 oxE4(228): <228> 235 oxE5(229): <229> 236 oxE6(230): <230> 237 oxE7(231): <231> 238 oxE8(232): <232> 239 oxE9(233): <233> 240 oxEA(234): <234> 241 oxEB(235): <235> 242 oxEC(236): <236> 243 oxED(237): <237> 244 oxEE(238): <238> 245 oxEF(239): <239> 246 oxF0(240): <240> 247 oxF1(241): <241> 248 oxF2(242): <242> 249 oxF3(243): <243> 250 oxF4(244): <244> 251 oxF5(245): <245> 252 oxF6(246): <246> 253 oxF7(247): <247> 254 oxF8(248): <248> 255 oxF9(249): <249> 256 oxFA(250): <250> 257 oxFB(251): <251> 258 oxFC(252): <252> 259 oxFD(253): <253> 260 oxFE(254): <254> 261 oxFF(255): <255>
“<n>”形式:是未使用的操作码。
“字节码”,是指令以字节为单位,最多只能表示256个不同的字节码指令。实际上Python只用了101条字节码指令:
>>> import opcode >>> import re >>> [op for op in opcode.opname if re.search(r'^<\d*>$',op)] ['<0>', '<6>', '<7>', '<8>', '<13>', '<14>', '<16>', '<17>', '<18>', '<21>', '<30>', '<31>', '<32>', '<33>', '<34>', '<35>', '<36>', '<37>', '<38>', '<39>', '<40>', '<41>', '<42>', '<43>', '<44>', '<45>', '<46>', '<47>', '<48>', '<49>', '<50>', '<51>', '<52>', '<53>', '<58>', '<73>', '<74>', '<82>', '<85>', '<99>', '<117>', '<118>', '<123>', '<127>', '<128>', '<129>', '<139>', '<148>', '<149>', '<150>', '<151>', '<152>', '<153>', '<154>', '<155>', '<156>', '<157>', '<158>', '<159>', '<160>', '<161>', '<162>', '<163>', '<164>', '<165>', '<166>', '<167>', '<168>', '<169>', '<170>', '<171>', '<172>', '<173>', '<174>', '<175>', '<176>', '<177>', '<178>', '<179>', '<180>', '<181>', '<182>', '<183>', '<184>', '<185>', '<186>', '<187>', '<188>', '<189>', '<190>', '<191>', '<192>', '<193>', '<194>', '<195>', '<196>', '<197>', '<198>', '<199>', '<200>', '<201>', '<202>', '<203>', '<204>', '<205>', '<206>', '<207>', '<208>', '<209>', '<210>', '<211>', '<212>', '<213>', '<214>', '<215>', '<216>', '<217>', '<218>', '<219>', '<220>', '<221>', '<222>', '<223>', '<224>', '<225>', '<226>', '<227>', '<228>', '<229>', '<230>', '<231>', '<232>', '<233>', '<234>', '<235>', '<236>', '<237>', '<238>', '<239>', '<240>', '<241>', '<242>', '<243>', '<244>', '<245>', '<246>', '<247>', '<248>', '<249>', '<250>', '<251>', '<252>', '<253>', '<254>', '<255>'] >>> [op for op in opcode.opname if not re.search(r'^<\d*>$',op)] ['POP_TOP', 'ROT_TWO', 'ROT_THREE', 'DUP_TOP', 'DUP_TOP_TWO', 'NOP', 'UNARY_POSITIVE', 'UNARY_NEGATIVE', 'UNARY_NOT', 'UNARY_INVERT', 'BINARY_POWER', 'BINARY_MULTIPLY', 'BINARY_MODULO', 'BINARY_ADD', 'BINARY_SUBTRACT', 'BINARY_SUBSCR', 'BINARY_FLOOR_DIVIDE', 'BINARY_TRUE_DIVIDE', 'INPLACE_FLOOR_DIVIDE', 'INPLACE_TRUE_DIVIDE', 'STORE_MAP', 'INPLACE_ADD', 'INPLACE_SUBTRACT', 'INPLACE_MULTIPLY', 'INPLACE_MODULO', 'STORE_SUBSCR', 'DELETE_SUBSCR', 'BINARY_LSHIFT', 'BINARY_RSHIFT', 'BINARY_AND', 'BINARY_XOR', 'BINARY_OR', 'INPLACE_POWER', 'GET_ITER', 'STORE_LOCALS', 'PRINT_EXPR', 'LOAD_BUILD_CLASS', 'YIELD_FROM', 'INPLACE_LSHIFT', 'INPLACE_RSHIFT', 'INPLACE_AND', 'INPLACE_XOR', 'INPLACE_OR', 'BREAK_LOOP', 'WITH_CLEANUP', 'RETURN_VALUE', 'IMPORT_STAR', 'YIELD_VALUE', 'POP_BLOCK', 'END_FINALLY', 'POP_EXCEPT', 'STORE_NAME', 'DELETE_NAME', 'UNPACK_SEQUENCE', 'FOR_ITER', 'UNPACK_EX', 'STORE_ATTR', 'DELETE_ATTR', 'STORE_GLOBAL', 'DELETE_GLOBAL', 'LOAD_CONST', 'LOAD_NAME', 'BUILD_TUPLE', 'BUILD_LIST', 'BUILD_SET', 'BUILD_MAP', 'LOAD_ATTR', 'COMPARE_OP', 'IMPORT_NAME', 'IMPORT_FROM', 'JUMP_FORWARD', 'JUMP_IF_FALSE_OR_POP', 'JUMP_IF_TRUE_OR_POP', 'JUMP_ABSOLUTE', 'POP_JUMP_IF_FALSE', 'POP_JUMP_IF_TRUE', 'LOAD_GLOBAL', 'CONTINUE_LOOP', 'SETUP_LOOP', 'SETUP_EXCEPT', 'SETUP_FINALLY', 'LOAD_FAST', 'STORE_FAST', 'DELETE_FAST', 'RAISE_VARARGS', 'CALL_FUNCTION', 'MAKE_FUNCTION', 'BUILD_SLICE', 'MAKE_CLOSURE', 'LOAD_CLOSURE', 'LOAD_DEREF', 'STORE_DEREF', 'DELETE_DEREF', 'CALL_FUNCTION_VAR', 'CALL_FUNCTION_KW', 'CALL_FUNCTION_VAR_KW', 'SETUP_WITH', 'EXTENDED_ARG', 'LIST_APPEND', 'SET_ADD', 'MAP_ADD'] >>> len([op for op in opcode.opname if not re.search(r'^<\d*>$',op)]) 101 >>> len(opcode.opmap) 101
字节码指令的编码小于90的为无参数的,指令仅包含操作码自身,共1字节;大于等于90的,则每条指令在码之后还带有1个参数,参数长度为2字节,共3字节。 指令后的参数大于2个字节的情况:见后面的指令含义介绍部分的EXTENDED_ARG(ext)。
Python程序的字节码在运行时以PyStringObject的形式保存在PyCodeObject的co_code域里(前面的PyCodeObject一节已介绍过)。co_code域只含有指令而不包含别的程序数据;变量名、常量等数据均放在别的域里。
获取编码为88的指令码和获取指令码为'END_FINALLY'的编码:
>>> import opcode >>> opcode.opname[88] 'END_FINALLY' >>> opcode.opmap['END_FINALLY'] 88
opcode模块所在的文件:
>>> opcode.__file__ 'D:\\Python33\\lib\\opcode.py'
1 """ 2 opcode module - potentially shared between dis and other modules which 3 operate on bytecodes (e.g. peephole optimizers). 4 """ 5 6 __all__ = ["cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs", 7 "haslocal", "hascompare", "hasfree", "opname", "opmap", 8 "HAVE_ARGUMENT", "EXTENDED_ARG", "hasnargs"] 9 10 cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not in', 'is', 11 'is not', 'exception match', 'BAD') 12 13 hasconst = [] 14 hasname = [] 15 hasjrel = [] 16 hasjabs = [] 17 haslocal = [] 18 hascompare = [] 19 hasfree = [] 20 hasnargs = [] 21 22 opmap = {} 23 opname = [''] * 256 24 for op in range(256): opname[op] = '<%r>' % (op,) #initial opname ,['<0>', '<1>', '<2>', ..., '<255>'] 25 del op 26 27 def def_op(name, op): 28 opname[op] = name 29 opmap[name] = op 30 31 def name_op(name, op): 32 def_op(name, op) 33 hasname.append(op) 34 35 def jrel_op(name, op): 36 def_op(name, op) 37 hasjrel.append(op) 38 39 def jabs_op(name, op): 40 def_op(name, op) 41 hasjabs.append(op) 42 43 # Instruction opcodes for compiled code 44 # Blank lines correspond to available opcodes 45 46 def_op('POP_TOP', 1) 47 def_op('ROT_TWO', 2) 48 def_op('ROT_THREE', 3) 49 def_op('DUP_TOP', 4) 50 def_op('DUP_TOP_TWO', 5) 51 52 def_op('NOP', 9) 53 def_op('UNARY_POSITIVE', 10) 54 def_op('UNARY_NEGATIVE', 11) 55 def_op('UNARY_NOT', 12) 56 57 def_op('UNARY_INVERT', 15) 58 59 def_op('BINARY_POWER', 19) 60 def_op('BINARY_MULTIPLY', 20) 61 62 def_op('BINARY_MODULO', 22) 63 def_op('BINARY_ADD', 23) 64 def_op('BINARY_SUBTRACT', 24) 65 def_op('BINARY_SUBSCR', 25) 66 def_op('BINARY_FLOOR_DIVIDE', 26) 67 def_op('BINARY_TRUE_DIVIDE', 27) 68 def_op('INPLACE_FLOOR_DIVIDE', 28) 69 def_op('INPLACE_TRUE_DIVIDE', 29) 70 71 def_op('STORE_MAP', 54) 72 def_op('INPLACE_ADD', 55) 73 def_op('INPLACE_SUBTRACT', 56) 74 def_op('INPLACE_MULTIPLY', 57) 75 76 def_op('INPLACE_MODULO', 59) 77 def_op('STORE_SUBSCR', 60) 78 def_op('DELETE_SUBSCR', 61) 79 def_op('BINARY_LSHIFT', 62) 80 def_op('BINARY_RSHIFT', 63) 81 def_op('BINARY_AND', 64) 82 def_op('BINARY_XOR', 65) 83 def_op('BINARY_OR', 66) 84 def_op('INPLACE_POWER', 67) 85 def_op('GET_ITER', 68) 86 def_op('STORE_LOCALS', 69) 87 88 def_op('PRINT_EXPR', 70) 89 def_op('LOAD_BUILD_CLASS', 71) 90 def_op('YIELD_FROM', 72) 91 92 def_op('INPLACE_LSHIFT', 75) 93 def_op('INPLACE_RSHIFT', 76) 94 def_op('INPLACE_AND', 77) 95 def_op('INPLACE_XOR', 78) 96 def_op('INPLACE_OR', 79) 97 def_op('BREAK_LOOP', 80) 98 def_op('WITH_CLEANUP', 81) 99 100 def_op('RETURN_VALUE', 83) 101 def_op('IMPORT_STAR', 84) 102 103 def_op('YIELD_VALUE', 86) 104 def_op('POP_BLOCK', 87) 105 def_op('END_FINALLY', 88) 106 def_op('POP_EXCEPT', 89) 107 108 HAVE_ARGUMENT = 90 # Opcodes from here have an argument: 109 110 name_op('STORE_NAME', 90) # Index in name list 111 name_op('DELETE_NAME', 91) # "" 112 def_op('UNPACK_SEQUENCE', 92) # Number of tuple items 113 jrel_op('FOR_ITER', 93) 114 def_op('UNPACK_EX', 94) 115 name_op('STORE_ATTR', 95) # Index in name list 116 name_op('DELETE_ATTR', 96) # "" 117 name_op('STORE_GLOBAL', 97) # "" 118 name_op('DELETE_GLOBAL', 98) # "" 119 def_op('LOAD_CONST', 100) # Index in const list 120 hasconst.append(100) 121 name_op('LOAD_NAME', 101) # Index in name list 122 def_op('BUILD_TUPLE', 102) # Number of tuple items 123 def_op('BUILD_LIST', 103) # Number of list items 124 def_op('BUILD_SET', 104) # Number of set items 125 def_op('BUILD_MAP', 105) # Number of dict entries (upto 255) 126 name_op('LOAD_ATTR', 106) # Index in name list 127 def_op('COMPARE_OP', 107) # Comparison operator 128 hascompare.append(107) 129 name_op('IMPORT_NAME', 108) # Index in name list 130 name_op('IMPORT_FROM', 109) # Index in name list 131 132 jrel_op('JUMP_FORWARD', 110) # Number of bytes to skip 133 jabs_op('JUMP_IF_FALSE_OR_POP', 111) # Target byte offset from beginning of code 134 jabs_op('JUMP_IF_TRUE_OR_POP', 112) # "" 135 jabs_op('JUMP_ABSOLUTE', 113) # "" 136 jabs_op('POP_JUMP_IF_FALSE', 114) # "" 137 jabs_op('POP_JUMP_IF_TRUE', 115) # "" 138 139 name_op('LOAD_GLOBAL', 116) # Index in name list 140 141 jabs_op('CONTINUE_LOOP', 119) # Target address 142 jrel_op('SETUP_LOOP', 120) # Distance to target address 143 jrel_op('SETUP_EXCEPT', 121) # "" 144 jrel_op('SETUP_FINALLY', 122) # "" 145 146 def_op('LOAD_FAST', 124) # Local variable number 147 haslocal.append(124) 148 def_op('STORE_FAST', 125) # Local variable number 149 haslocal.append(125) 150 def_op('DELETE_FAST', 126) # Local variable number 151 haslocal.append(126) 152 153 def_op('RAISE_VARARGS', 130) # Number of raise arguments (1, 2, or 3) 154 def_op('CALL_FUNCTION', 131) # #args + (#kwargs << 8) 155 hasnargs.append(131) 156 def_op('MAKE_FUNCTION', 132) # Number of args with default values 157 def_op('BUILD_SLICE', 133) # Number of items 158 def_op('MAKE_CLOSURE', 134) 159 def_op('LOAD_CLOSURE', 135) 160 hasfree.append(135) 161 def_op('LOAD_DEREF', 136) 162 hasfree.append(136) 163 def_op('STORE_DEREF', 137) 164 hasfree.append(137) 165 def_op('DELETE_DEREF', 138) 166 hasfree.append(138) 167 168 def_op('CALL_FUNCTION_VAR', 140) # #args + (#kwargs << 8) 169 hasnargs.append(140) 170 def_op('CALL_FUNCTION_KW', 141) # #args + (#kwargs << 8) 171 hasnargs.append(141) 172 def_op('CALL_FUNCTION_VAR_KW', 142) # #args + (#kwargs << 8) 173 hasnargs.append(142) 174 175 jrel_op('SETUP_WITH', 143) 176 177 def_op('LIST_APPEND', 145) 178 def_op('SET_ADD', 146) 179 def_op('MAP_ADD', 147) 180 181 def_op('EXTENDED_ARG', 144) 182 EXTENDED_ARG = 144 183 184 del def_op, name_op, jrel_op, jabs_op
各字节码指令的含义:http://docs.python.org/3/library/dis.html
31.12.1. Python Bytecode Instructions
The Python compiler currently generates the following bytecode instructions.
General instructions
- NOP
-
Do nothing code. Used as a placeholder by the bytecode optimizer.
- POP_TOP
-
Removes the top-of-stack (TOS) item.
- 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.
- DUP_TOP
-
Duplicates the reference on top of the stack.
- DUP_TOP_TWO
-
Duplicates the two references on top of the stack, leaving them in the same order.
Unary operations
Unary operations take the top of the stack, apply the operation, and push the result back on the stack.
- UNARY_POSITIVE
-
Implements TOS = +TOS.
- UNARY_NEGATIVE
-
Implements TOS = -TOS.
- UNARY_NOT
-
Implements TOS = not TOS.
- UNARY_INVERT
-
Implements TOS = ~TOS.
- GET_ITER
-
Implements TOS = iter(TOS).
Binary operations
Binary operations remove the top of the stack (TOS) and the second top-most stack item (TOS1) from the stack. They perform the operation, and put the result back on the stack.
- BINARY_POWER
-
Implements TOS = TOS1 ** TOS.
- BINARY_MULTIPLY
-
Implements TOS = TOS1 * TOS.
- BINARY_FLOOR_DIVIDE
-
Implements TOS = TOS1 // TOS.
- BINARY_TRUE_DIVIDE
-
Implements TOS = TOS1 / TOS.
- BINARY_MODULO
-
Implements TOS = TOS1 % TOS.
- BINARY_ADD
-
Implements TOS = TOS1 + TOS.
- BINARY_SUBTRACT
-
Implements TOS = TOS1 - TOS.
- BINARY_SUBSCR
-
Implements TOS = TOS1[TOS].
- BINARY_LSHIFT
-
Implements TOS = TOS1 << TOS.
- BINARY_RSHIFT
-
Implements TOS = TOS1 >> TOS.
- BINARY_AND
-
Implements TOS = TOS1 & TOS.
- BINARY_XOR
-
Implements TOS = TOS1 ^ TOS.
- BINARY_OR
-
Implements TOS = TOS1 | TOS.
In-place operations
In-place operations are like binary operations, in that they remove TOS and TOS1, and push the result back on the stack, but the operation is done in-place when TOS1 supports it, and the resulting TOS may be (but does not have to be) the original TOS1.
- INPLACE_POWER
-
Implements in-place TOS = TOS1 ** TOS.
- INPLACE_MULTIPLY
-
Implements in-place TOS = TOS1 * TOS.
- INPLACE_FLOOR_DIVIDE
-
Implements in-place TOS = TOS1 // TOS.
- INPLACE_TRUE_DIVIDE
-
Implements in-place TOS = TOS1 / TOS.
- INPLACE_MODULO
-
Implements in-place TOS = TOS1 % TOS.
- INPLACE_ADD
-
Implements in-place TOS = TOS1 + TOS.
- INPLACE_SUBTRACT
-
Implements in-place TOS = TOS1 - TOS.
- INPLACE_LSHIFT
-
Implements in-place TOS = TOS1 << TOS.
- INPLACE_RSHIFT
-
Implements in-place TOS = TOS1 >> TOS.
- INPLACE_AND
-
Implements in-place TOS = TOS1 & TOS.
- INPLACE_XOR
-
Implements in-place TOS = TOS1 ^ TOS.
- INPLACE_OR
-
Implements in-place TOS = TOS1 | TOS.
- STORE_SUBSCR
-
Implements TOS1[TOS] = TOS2.
- DELETE_SUBSCR
-
Implements del TOS1[TOS].
Miscellaneous opcodes
- PRINT_EXPR
-
Implements the expression statement for the interactive mode. TOS is removed from the stack and printed. In non-interactive mode, an expression statement is terminated with POP_STACK.
- BREAK_LOOP
-
Terminates a loop due to a break statement.
- CONTINUE_LOOP(target)
-
Continues a loop due to a continue statement. target is the address to jump to (which should be a FOR_ITER instruction).
- SET_ADD(i)
-
Calls set.add(TOS1[-i], TOS). Used to implement set comprehensions.
- LIST_APPEND(i)
-
Calls list.append(TOS[-i], TOS). Used to implement list comprehensions.
- MAP_ADD(i)
-
Calls dict.setitem(TOS1[-i], TOS, TOS1). Used to implement dict comprehensions.
For all of the SET_ADD, LIST_APPEND and MAP_ADD instructions, while the added value or key/value pair is popped off, the container object remains on the stack so that it is available for further iterations of the loop.
- RETURN_VALUE
-
Returns with TOS to the caller of the function.
- YIELD_VALUE
-
Pops TOS and yields it from a generator.
- YIELD_FROM
-
Pops TOS and delegates to it as a subiterator from a generator.
New in version 3.3.
- IMPORT_STAR
-
Loads all symbols not starting with '_' directly from the module TOS to the local namespace. The module is popped after loading all names. This opcode implements from module import *.
- POP_BLOCK
-
Removes one block from the block stack. Per frame, there is a stack of blocks, denoting nested loops, try statements, and such.
- POP_EXCEPT
-
Removes one block from the block stack. The popped block must be an exception handler block, as implicitly created when entering an except handler. In addition to popping extraneous values from the frame stack, the last three popped values are used to restore the exception state.
- END_FINALLY
-
Terminates a finally clause. The interpreter recalls whether the exception has to be re-raised, or whether the function returns, and continues with the outer-next block.
- LOAD_BUILD_CLASS
-
Pushes builtins.__build_class__() onto the stack. It is later called by CALL_FUNCTION to construct a class.
- SETUP_WITH(delta)
-
This opcode performs several operations before a with block starts. First, it loads __exit__() from the context manager and pushes it onto the stack for later use by WITH_CLEANUP. Then, __enter__() is called, and a finally block pointing to delta is pushed. Finally, the result of calling the enter method is pushed onto the stack. The next opcode will either ignore it (POP_TOP), or store it in (a) variable(s) (STORE_FAST, STORE_NAME, or UNPACK_SEQUENCE).
- WITH_CLEANUP
-
Cleans up the stack when a with statement block exits. TOS is the context manager’s __exit__() bound method. Below TOS are 1–3 values indicating how/why the finally clause was entered:
- SECOND = None
- (SECOND, THIRD) = (WHY_{RETURN,CONTINUE}), retval
- SECOND = WHY_*; no retval below it
- (SECOND, THIRD, FOURTH) = exc_info()
In the last case, TOS(SECOND, THIRD, FOURTH) is called, otherwise TOS(None, None, None). In addition, TOS is removed from the stack.
If the stack represents an exception, and the function call returns a ‘true’ value, this information is “zapped” and replaced with a single WHY_SILENCED to prevent END_FINALLY from re-raising the exception. (But non-local gotos will still be resumed.)
- STORE_LOCALS
-
Pops TOS from the stack and stores it as the current frame’s f_locals. This is used in class construction.
All of the following opcodes expect arguments. An argument is two bytes, with the more significant byte last.
- STORE_NAME(namei)
-
Implements name = TOS. namei is the index of name in the attribute co_names of the code object. The compiler tries to use STORE_FAST orSTORE_GLOBAL if possible.
- DELETE_NAME(namei)
-
Implements del name, where namei is the index into co_names attribute of the code object.
- UNPACK_SEQUENCE(count)
-
Unpacks TOS into count individual values, which are put onto the stack right-to-left.
- UNPACK_EX(counts)
-
Implements assignment with a starred target: Unpacks an iterable in TOS into individual values, where the total number of values can be smaller than the number of items in the iterable: one the new values will be a list of all leftover items.
The low byte of counts is the number of values before the list value, the high byte of counts the number of values after it. The resulting values are put onto the stack right-to-left.
- STORE_ATTR(namei)
-
Implements TOS.name = TOS1, where namei is the index of name in co_names.
- DELETE_ATTR(namei)
-
Implements del TOS.name, using namei as index into co_names.
- STORE_GLOBAL(namei)
-
Works as STORE_NAME, but stores the name as a global.
- DELETE_GLOBAL(namei)
-
Works as DELETE_NAME, but deletes a global name.
- LOAD_CONST(consti)
-
Pushes co_consts[consti] onto the stack.
- LOAD_NAME(namei)
-
Pushes the value associated with co_names[namei] onto the stack.
- BUILD_TUPLE(count)
-
Creates a tuple consuming count items from the stack, and pushes the resulting tuple onto the stack.
- BUILD_LIST(count)
-
Works as BUILD_TUPLE, but creates a list.
- BUILD_SET(count)
-
Works as BUILD_TUPLE, but creates a set.
- BUILD_MAP(count)
-
Pushes a new dictionary object onto the stack. The dictionary is pre-sized to hold count entries.
- LOAD_ATTR(namei)
-
Replaces TOS with getattr(TOS, co_names[namei]).
- COMPARE_OP(opname)
-
Performs a Boolean operation. The operation name can be found in cmp_op[opname].
- IMPORT_NAME(namei)
-
Imports the module co_names[namei]. TOS and TOS1 are popped and provide the fromlist and level arguments of __import__(). The module object is pushed onto the stack. The current namespace is not affected: for a proper import statement, a subsequent STORE_FAST instruction modifies the namespace.
- IMPORT_FROM(namei)
-
Loads the attribute co_names[namei] from the module found in TOS. The resulting object is pushed onto the stack, to be subsequently stored by aSTORE_FAST instruction.
- JUMP_FORWARD(delta)
-
Increments bytecode counter by delta.
- POP_JUMP_IF_TRUE(target)
-
If TOS is true, sets the bytecode counter to target. TOS is popped.
- POP_JUMP_IF_FALSE(target)
-
If TOS is false, sets the bytecode counter to target. TOS is popped.
- JUMP_IF_TRUE_OR_POP(target)
-
If TOS is true, sets the bytecode counter to target and leaves TOS on the stack. Otherwise (TOS is false), TOS is popped.
- JUMP_IF_FALSE_OR_POP(target)
-
If TOS is false, sets the bytecode counter to target and leaves TOS on the stack. Otherwise (TOS is true), TOS is popped.
- JUMP_ABSOLUTE(target)
-
Set bytecode counter to target.
- FOR_ITER(delta)
-
TOS is an iterator. Call its __next__() method. If this yields a new value, push it on the stack (leaving the iterator below it). If the iterator indicates it is exhausted TOS is popped, and the byte code counter is incremented by delta.
- LOAD_GLOBAL(namei)
-
Loads the global named co_names[namei] onto the stack.
- SETUP_LOOP(delta)
-
Pushes a block for a loop onto the block stack. The block spans from the current instruction with a size of delta bytes.
- SETUP_EXCEPT(delta)
-
Pushes a try block from a try-except clause onto the block stack. delta points to the first except block.
- SETUP_FINALLY(delta)
-
Pushes a try block from a try-except clause onto the block stack. delta points to the finally block.
- STORE_MAP
-
Store a key and value pair in a dictionary. Pops the key and value while leaving the dictionary on the stack.
- LOAD_FAST(var_num)
-
Pushes a reference to the local co_varnames[var_num] onto the stack.
- STORE_FAST(var_num)
-
Stores TOS into the local co_varnames[var_num].
- DELETE_FAST(var_num)
-
Deletes local co_varnames[var_num].
- LOAD_CLOSURE(i)
-
Pushes a reference to the cell contained in slot i of the cell and free variable storage. The name of the variable is co_cellvars[i] if i is less than the length of co_cellvars. Otherwise it is co_freevars[i - len(co_cellvars)].
- LOAD_DEREF(i)
-
Loads the cell contained in slot i of the cell and free variable storage. Pushes a reference to the object the cell contains on the stack.
- STORE_DEREF(i)
-
Stores TOS into the cell contained in slot i of the cell and free variable storage.
- DELETE_DEREF(i)
-
Empties the cell contained in slot i of the cell and free variable storage. Used by the del statement.
- RAISE_VARARGS(argc)
-
Raises an exception. argc indicates the number of parameters to the raise statement, ranging from 0 to 3. The handler will find the traceback as TOS2, the parameter as TOS1, and the exception as TOS.
- CALL_FUNCTION(argc)
-
Calls a function. The low byte of argc indicates the number of positional parameters, the high byte the number of keyword parameters. On the stack, the opcode finds the keyword parameters first. For each keyword argument, the value is on top of the key. Below the keyword parameters, the positional parameters are on the stack, with the right-most parameter on top. Below the parameters, the function object to call is on the stack. Pops all function arguments, and the function itself off the stack, and pushes the return value.
- MAKE_FUNCTION(argc)
-
Pushes a new function object on the stack. TOS is the qualified name of the function; TOS1 is the code associated with the function. The function object is defined to have argc default parameters, which are found below TOS1.
- MAKE_CLOSURE(argc)
-
Creates a new function object, sets its __closure__ slot, and pushes it on the stack. TOS is the qualified name of the function, TOS1 is the code associated with the function, and TOS2 is the tuple containing cells for the closure’s free variables. The function also has argc default parameters, which are found below the cells.
- BUILD_SLICE(argc)
-
Pushes a slice object on the stack. argc must be 2 or 3. If it is 2, slice(TOS1, TOS) is pushed; if it is 3, slice(TOS2, TOS1, TOS) is pushed. See theslice() built-in function for more information.
- EXTENDED_ARG(ext)
-
Prefixes any opcode which has an argument too big to fit into the default two bytes. ext holds two additional bytes which, taken together with the subsequent opcode’s argument, comprise a four-byte argument, ext being the two most-significant bytes.
- CALL_FUNCTION_VAR(argc)
-
Calls a function. argc is interpreted as in CALL_FUNCTION. The top element on the stack contains the variable argument list, followed by keyword and positional arguments.
- CALL_FUNCTION_KW(argc)
-
Calls a function. argc is interpreted as in CALL_FUNCTION. The top element on the stack contains the keyword arguments dictionary, followed by explicit keyword and positional arguments.
- CALL_FUNCTION_VAR_KW(argc)
-
Calls a function. argc is interpreted as in CALL_FUNCTION. The top element on the stack contains the keyword arguments dictionary, followed by the variable-arguments tuple, followed by explicit keyword and positional arguments.
- HAVE_ARGUMENT
-
This is not really an opcode. It identifies the dividing line between opcodes which don’t take arguments < HAVE_ARGUMENT and those which do >=HAVE_ARGUMENT.
简单分析一个函数的字节码:
>>> import dis >>> def f(x, y): return x + y >>> dis.dis(f) 2 0 LOAD_FAST 0 (x) 3 LOAD_FAST 1 (y) 6 BINARY_ADD 7 RETURN_VALUE >>> f.__code__.co_varnames ('x', 'y') >>> f.__code__.co_varnames[0] 'x' >>> f.__code__.co_varnames[1] 'y'
dis.dis(f)的显示结果说明:
例如:2 0 LOAD_FAST 0 (x)
最左边的一列显示的是字节码指令对应的源码中行数,左起第2列显示的是当前的字节码指令在co_code中的偏移位置,第3列显示的是当前的字节码指令,最后一列显示的是当期字节码指令的参数。
其中三条指令的含义:
(1)LOAD_FAST(var_num):Pushes a reference to the local co_varnames[var_num] onto the stack.
(2)BINARY_ADD:Implements TOS = TOS1 + TOS.
(3)RETURN_VALUE:Returns with TOS to the caller of the function.