Why is it possible to use more than 2 ^ 16 constants in a Python function?
-
21-12-2019 - |
Question
In internal modules like peephole, argument of LOAD_CONST
is stored in the two bytes following the opcode
.
For example, the macro it uses to get argument of an operation is implemented as:
#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
The argument of LOAD_CONST
is an index into the consts
array.
So I guessed maybe we can only use at most 2 ^ 16 constants in a Python function.
But when I experiment with a function that use 66666 (> 65536) constants, it still runs normally.
What could be the reason?
Solution
From the dis
docs:
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.
If an opcode needs an argument longer than 2 bytes, an EXTENDED_ARG opcode provides 2 more bytes of argument.