Search code examples
pythoncpythonno-op

How to get the Python interpreter to emit a NOP instruction?


Is there any way to get Python's interpreter to compile any Python code into a NOP instruction?

(I'm specifically talking about obtaining bytecode via compiling Python code, not generating it directly.)


Solution

  • At the time the question was asked, this was impossible. NOP opcodes were only generated by the peephole optimizer, but the last step of peephole optimization removed all NOPs and retargeted jumps for the new instruction indices.

    In fact, barring bugs, this seems likely to have been impossible in every Python version before that point too. In Python 2.3, there was no NOP opcode, and in Python 2.4, the peephole optimizer already removed all NOPs it generated.


    Since then, the use of NOP instructions has changed. NOPs are now generated, and preserved in the final bytecode, for any line of "executable" code that would otherwise have no bytecode associated with it. So for example, something like

    pass
    

    becomes a NOP, as long as no other bytecode would have been associated with that line. On the other hand, something like global x is considered declarative instead of "executable", so it doesn't get a NOP. Docstrings also seem to be excluded.

    This is used for debugging support, to ensure that debuggers step through every line "executed", even if "executing" a line doesn't actually do anything. The relevant PEP is PEP 626.