百度上目前還搜不到 Python 字節碼全套內容,於是搭了梯子爬了下官方的教程。
我們都知道 python 是解釋性語言,但 python 還有個編譯過程,這個過程是將 python 代碼編譯成 字節碼,類似於彙編語言的一條一條指令。執行時,首先會讀取指令,底層的 C 語言代碼中寫有上千行的 switch case 語句與這個指令相匹配並執行相關代碼。
下面就是 python 字節碼大全,了解字節碼有助於我們更深入地熟悉 python 代碼的執行。
Do nothing code. Used as a placeholder by the bytecode optimizer.
Removes the top-of-stack (TOS) item.
Swaps the two top-most stack items.
Lifts second and third stack item one position up, moves top down to positionthree.
Lifts second, third and forth stack items one position up, moves top downto position four.
Duplicates the reference on top of the stack.
Duplicates the two references on top of the stack, leaving them in thesame order.
Implements TOS = not TOS.
Implements TOS = iter(TOS).
If TOS is a generator iterator or coroutine objectit is left as is. Otherwise, implements TOS = iter(TOS).
Implements TOS = TOS1 ** TOS.
Implements TOS = TOS1 * TOS.
Implements TOS = TOS1 @ TOS.
Implements TOS = TOS1 // TOS.
Implements TOS = TOS1 / TOS.
Implements TOS = TOS1 % TOS.
Implements TOS = TOS1 + TOS.
Implements TOS = TOS1 - TOS.
Implements TOS = TOS1[TOS].
Implements TOS = TOS1 << TOS.
Implements TOS = TOS1 >> TOS.
Implements TOS = TOS1 & TOS.
Implements TOS = TOS1 ^ TOS.
Implements TOS = TOS1 | TOS.
Implements in-place TOS = TOS1 ** TOS.
Implements in-place TOS = TOS1 * TOS.
Implements in-place TOS = TOS1 @ TOS.
Implements in-place TOS = TOS1 // TOS.
Implements in-place TOS = TOS1 / TOS.
Implements in-place TOS = TOS1 % TOS.
Implements in-place TOS = TOS1 + TOS.
Implements in-place TOS = TOS1 - TOS.
Implements in-place TOS = TOS1 << TOS.
Implements in-place TOS = TOS1 >> TOS.
Implements in-place TOS = TOS1 & TOS.
Implements in-place TOS = TOS1 ^ TOS.
Implements in-place TOS = TOS1 | TOS.
Implements TOS1[TOS] = TOS2.
Implements del TOS1[TOS].
Implements TOS = get_awaitable(TOS), where get_awaitable(o)returns o if o is a coroutine object or a generator object withthe CO_ITERABLE_COROUTINE flag, or resolveso.await.
Implements TOS = TOS.aiter().
Implements PUSH(get_awaitable(TOS.anext())). See GET_AWAITABLEfor details about get_awaitable
Terminates an async for loop. Handles an exception raisedwhen awaiting a next item. If TOS is StopAsyncIteration pop 7values from the stack and restore the exception state using the secondthree of them. Otherwise re-raise the exception using the three valuesfrom the stack. An exception handler block is removed from the block stack.
Resolves aenter and aexit from the object on top of thestack. Pushes aexit and result of aenter() to the stack.
Creates a new frame object.
Implements the expression statement for the interactive mode. TOS is removedfrom the stack and printed. In non-interactive mode, an expression statementis terminated with POP_TOP.
Calls set.add(TOS1[-i], TOS). Used to implement set comprehensions.
Calls list.append(TOS[-i], TOS). Used to implement list comprehensions.
Calls dict.setitem(TOS1[-i], TOS1, TOS). Used to implement dictcomprehensions.
Returns with TOS to the caller of the function.
Pops TOS and yields it from a generator.
Pops TOS and delegates to it as a subiterator from a generator.
Checks whether annotations is defined in locals(), if not it isset up to an empty dict. This opcode is only emitted if a classor module body contains variable annotationsstatically.
Loads all symbols not starting with '_' directly from the module TOS tothe local namespace. The module is popped after loading all names. Thisopcode implements from module import *.
Removes one block from the block stack. Per frame, there is a stack ofblocks, denoting try statements, and such.
Removes one block from the block stack. The popped block must be an exceptionhandler block, as implicitly created when entering an except handler. Inaddition to popping extraneous values from the frame stack, the last threepopped values are used to restore the exception state.
Cleans up the value stack and the block stack. If preserve_tos is not0 TOS first is popped from the stack and pushed on the stack afterperforming other stack operations:
Pushes NULL onto the stack for using it in END_FINALLY,POP_FINALLY, WITH_CLEANUP_START andWITH_CLEANUP_FINISH. Starts the finally block.
Terminates a finally clause. The interpreter recalls whether theexception has to be re-raised or execution has to be continued depending onthe value of TOS.
Pushes builtins.build_class() onto the stack. It is later calledby CALL_FUNCTION to construct a class.
This opcode performs several operations before a with block starts. First,it loads exit() from the context manager and pushes it ontothe stack for later use by WITH_CLEANUP_START. Then,enter() is called, and a finally block pointing to deltais pushed. Finally, the result of calling the enter() method is pushed ontothe stack. The next opcode will either ignore it (POP_TOP), orstore it in (a) variable(s) (STORE_FAST, STORE_NAME, orUNPACK_SEQUENCE).
Starts cleaning up the stack when a with statement block exits.
Finishes cleaning up the stack when a with statement block exits.
Implements name = TOS. namei is the index of name in the attributeco_names of the code object. The compiler tries to useSTORE_FAST or STORE_GLOBAL if possible.
Implements del name, where namei is the index into co_namesattribute of the code object.
Unpacks TOS into count individual values, which are put onto the stackright-to-left.
Implements assignment with a starred target: Unpacks an iterable in TOS intoindividual values, where the total number of values can be smaller than thenumber of items in the iterable: one of the new values will be a list of allleftover items.
Implements TOS.name = TOS1, where namei is the index of name inco_names.
Implements del TOS.name, using namei as index into co_names.
Works as STORE_NAME, but stores the name as a global.
Works as DELETE_NAME, but deletes a global name.
Pushes co_consts[consti] onto the stack.
Pushes the value associated with co_names[namei] onto the stack.
Creates a tuple consuming count items from the stack, and pushes theresulting tuple onto the stack.
Works as BUILD_TUPLE, but creates a list.
Works as BUILD_TUPLE, but creates a set.
Pushes a new dictionary object onto the stack. Pops 2 * count itemsso that the dictionary holds count entries:{..., TOS3: TOS2, TOS1: TOS}.
The version of BUILD_MAP specialized for constant keys. Pops thetop element on the stack which contains a tuple of keys, then starting fromTOS1, pops count values to form values in the built dictionary.
Concatenates count strings from the stack and pushes the resulting stringonto the stack.
Pops count iterables from the stack, joins them in a single tuple,and pushes the result. Implements iterable unpacking in tupledisplays (*x, *y, *z).
BUILD_TUPLE_UNPACK_WITH_CALL
This is similar to BUILD_TUPLE_UNPACK,but is used for f(*x, *y, *z) call syntax. The stack item at positioncount + 1 should be the corresponding callable f.
This is similar to BUILD_TUPLE_UNPACK, but pushes a listinstead of tuple. Implements iterable unpacking in listdisplays [*x, *y, *z].
This is similar to BUILD_TUPLE_UNPACK, but pushes a setinstead of tuple. Implements iterable unpacking in setdisplays {*x, *y, *z}.
Pops count mappings from the stack, merges them into a single dictionary,and pushes the result. Implements dictionary unpacking in dictionarydisplays {*x, **y, *z}.
BUILD_MAP_UNPACK_WITH_CALL
This is similar to BUILD_MAP_UNPACK,but is used for f(*x, **y, *z) call syntax. The stack item atposition count + 2 should be the corresponding callable f.
Replaces TOS with getattr(TOS, co_names[namei]).
Performs a Boolean operation. The operation name can be found incmp_op[opname].
Imports the module co_names[namei]. TOS and TOS1 are popped and providethe fromlist and level arguments of import(). The moduleobject is pushed onto the stack. The current namespace is not affected: fora proper import statement, a subsequent STORE_FAST instructionmodifies the namespace.
Loads the attribute co_names[namei] from the module found in TOS. Theresulting object is pushed onto the stack, to be subsequently stored by aSTORE_FAST instruction.
Increments bytecode counter by delta.
If TOS is true, sets the bytecode counter to target. TOS is popped.
If TOS is false, sets the bytecode counter to target. TOS is popped.
If TOS is true, sets the bytecode counter to target and leaves TOS on thestack. Otherwise (TOS is false), TOS is popped.
If TOS is false, sets the bytecode counter to target and leaves TOS on thestack. Otherwise (TOS is true), TOS is popped.
Set bytecode counter to target.
TOS is an iterator. Call its next() method. Ifthis yields a new value, push it on the stack (leaving the iterator belowit). If the iterator indicates it is exhausted TOS is popped, and the bytecode counter is incremented by delta.
Loads the global named co_names[namei] onto the stack.
Pushes a try block from a try-finally or try-except clause onto the blockstack. delta points to the finally block or the first except block.
Pushes the address of the next instruction onto the stack and incrementsbytecode counter by delta. Used for calling the finally block as aâsubroutineâ.
Pushes a reference to the local co_varnames[var_num] onto the stack.
Stores TOS into the local co_varnames[var_num].
Deletes local co_varnames[var_num].
Pushes a reference to the cell contained in slot i of the cell and freevariable storage. The name of the variable is co_cellvars[i] if i isless than the length of co_cellvars. Otherwise it is co_freevars[i -len(co_cellvars)].
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.
Much like LOAD_DEREF but first checks the locals dictionary beforeconsulting the cell. This is used for loading free variables in classbodies.
Stores TOS into the cell contained in slot i of the cell and free variablestorage.
Empties the cell contained in slot i of the cell and free variable storage.Used by the del statement.
Raises an exception using one of the 3 forms of the raise statement,depending on the value of argc:
Calls a callable object with positional arguments.argc indicates the number of positional arguments.The top of the stack contains positional arguments, with the right-mostargument on top. Below the arguments is a callable object to call.CALL_FUNCTION pops all arguments and the callable object off the stack,calls the callable object with those arguments, and pushes the return valuereturned by the callable object.
Calls a callable object with positional (if any) and keyword arguments.argc indicates the total number of positional and keyword arguments.The top element on the stack contains a tuple of keyword argument names.Below that are keyword arguments in the order corresponding to the tuple.Below that are positional arguments, with the right-most parameter ontop. Below the arguments is a callable object to call.CALL_FUNCTION_KW pops all arguments and the callable object off the stack,calls the callable object with those arguments, and pushes the return valuereturned by the callable object.
Calls a callable object with variable set of positional and keywordarguments. If the lowest bit of flags is set, the top of the stackcontains a mapping object containing additional keyword arguments.Below that is an iterable object containing positional arguments anda callable object to call. BUILD_MAP_UNPACK_WITH_CALL andBUILD_TUPLE_UNPACK_WITH_CALL can be used for merging multiplemapping objects and iterables containing arguments.Before the callable is called, the mapping object and iterable objectare each âunpackedâ and their contents passed in as keyword andpositional arguments respectively.CALL_FUNCTION_EX pops all arguments and the callable object off the stack,calls the callable object with those arguments, and pushes the return valuereturned by the callable object.
Loads a method named co_names[namei] from the TOS object. TOS is popped.This bytecode distinguishes two cases: if TOS has a method with the correctname, the bytecode pushes the unbound method and TOS. TOS will be used asthe first argument (self) by CALL_METHOD when calling theunbound method. Otherwise, NULL and the object return by the attributelookup are pushed.
Calls a method. argc is the number of positional arguments.Keyword arguments are not supported. This opcode is designed to be usedwith LOAD_METHOD. Positional arguments are on top of the stack.Below them, the two items described in LOAD_METHOD are on thestack (either self and an unbound method object or NULL and anarbitrary callable). All of them are popped and the return value is pushed.
Pushes a new function object on the stack. From bottom to top, the consumedstack must consist of values if the argument carries a specified flag value
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) ispushed. See the slice() built-in function for more information.
Prefixes any opcode which has an argument too big to fit into the default onebyte. ext holds an additional byte which act as higher bits in the argument.For each opcode, at most three prefixal EXTENDED_ARG are allowed, formingan argument from two-byte to four-byte.
Used for implementing formatted literal strings (f-strings). Popsan optional fmt_spec from the stack, then a required value.flags is interpreted as follows:
This is not really an opcode. It identifies the dividing line betweenopcodes which donât use their argument and those that do(< HAVE_ARGUMENT and >= HAVE_ARGUMENT, respectively).
整理不易,點個讚叭,(#^.^#)