
On Sun, Oct 31, 2021 at 3:57 PM Steven D'Aprano <steve@pearwood.info> wrote:
Kind of like functions themselves :-)
>>> (lambda x, y: 2*x + 3**y).__code__.co_code b'd\x01|\x00\x14\x00d\x02|\x01\x13\x00\x17\x00S\x00'
The internal structure of that co_code object is a mystery, it is not part of the Python language, only of the implementation, but it remains a first-class value.
(My *guess* is that this may be the raw byte-code of the function body.)
It is; and fortunately, we have a handy tool for examining it:
dis.dis(b'd\x01|\x00\x14\x00d\x02|\x01\x13\x00\x17\x00S\x00') 0 LOAD_CONST 1 2 LOAD_FAST 0 4 BINARY_MULTIPLY 6 LOAD_CONST 2 8 LOAD_FAST 1 10 BINARY_POWER 12 BINARY_ADD 14 RETURN_VALUE
The exact meaning of this string depends on Python implementation and version. Importantly, though, this bytecode must be interpreted within a particular context (here, the context is the lambda function's code and the function itself), which provides meanings for consts and name lookups. There's no sensible way to inject this into some other function and expect it to mean "2*x + 3**y"; at best, it would actually take co_consts[1] * <co_varnames[0]> + co_consts[2] ** <co_varnames[1]>, but that might not mean anything either. ChrisA