CACHE opcode in Python 3.11 bytecode

Matthieu Dartiailh <[email protected]> Mon, 25 Jul 2022 22:45:03 +0200
Newsgroups gmane.comp.python.devel
Message-ID <[email protected]>
Hi all,

I am in the slow process of adding support for Python 3.11 in the 
bytecode project (https://github.com/MatthieuDartiailh/bytecode).

While attempting to update some tests I stumbled upon the need to 
include CACHE opcode to get things to work. For example, one can use 
bytecode to manually assemble the bytecode for the function:

def f():
     return 24 < 42

Under Python 3.10 it would look like:

f.__code__= Bytecode(
[
Instr("LOAD_CONST", 24),
Instr("LOAD_CONST", 42),
         Instr("COMPARE_OP", Compare.LT),
Instr("RETURN_VALUE"), ]
).to_code()


Under Python 3.11 I had to go to:

f.__code__= Bytecode(
[
Instr("RESUME", 0), Instr("LOAD_CONST", 24),
Instr("LOAD_CONST", 42),
         Instr("COMPARE_OP", Compare.LT), Instr("CACHE", 0), 
Instr("CACHE", 0),
Instr("RETURN_VALUE"), ]
).to_code()


Reading the doc for the dis module I understand the need for the RESUME 
instruction. However the documentation is rather vague in regard of CACHE.

In particular when using the first version, the code in the function 
ends up looking like '\x97\x00d\x00d\x01k\x00\x00\x00\x00\x00' even 
though bytecode generated '\x97\x00d\x00d\x01k\x00S\x00'. One can "see" 
that the two caches (\x00\x00\x00\x00) have been added automatically but 
the return disappeared. Is this a bug in 3.11 and if not where can I 
find more details regarding where one expect CACHE instructions to be 
present ?

Best

Matthieu C. Dartiailh

PS: I know the mailing list is going to be retired but I did not yet got 
everything configured for Discourse.