[Python-Dev] Why is Bytecode the way it is?
mwh at python.net
Thu Jul 8 11:57:40 CEST 2004
Paul Prescod <paul at prescod.net> writes:
> So I gave a tutorial last night on Python's implementation. I had a
> pretty clear idea of the parser, compiler, AST branch etc. But the
> bytecodes were fuzzy. For instance:
> >>> def foo(a):
> ... b = a + 5
> ... return b
> >>> dis.dis(foo)
> 2 0 LOAD_FAST 0 (a)
> 3 LOAD_CONST 1 (5)
> 6 BINARY_ADD
> 7 STORE_FAST 1 (b)
> 3 10 LOAD_FAST 1 (b)
> 13 RETURN_VALUE
> 14 LOAD_CONST 0 (None)
> 17 RETURN_VALUE
> Why does the RETURN_VALUE opcode have to return something from the
> stack? Why not have a RETURN_VAR opcode that would directly return a
> variable or constant? (a leading bit could indicate whether to look in
> the const or var tuple).
Well, you'd have to have RETURN_VAR *as well* as RETURN_VALUE, or in
return a + b
you'd have to create a temporary variable and store to it.
We have a limit of 256 opcodes...
> Similarly, what if BINARY_ADD could work directly on constants and
> variables? I see the virtue of using the stack for objects that do not
> otherwise have a name. But if a value is in a contant or variable, why
> not refer to it by its position in co_consts or co_varnames.
How would you implement this? Give BINARY_ADD two arguments
(something no bytecode has now, btw) and treat '-1' as 'pop from the
stack'? This sounds obfuscatory.
> And as long as we are talking about referring to things more directly,
> wouldn't it be possible to refer to constants by pointer rather than
> indirecting through the index? You'd have to fix up pointers when you
> first loaded the code but only once per function.
Could do. Opcode arguments are only 16 bits though, unless you use
the EXTENDED_ARG thingy, and then they're only 32 bits: what about 64
Python's VM is currently a stack machine. There are arguments for
making it a register machine, but if we want to do that, lets go the
whole hog and not have some kind of half-assed hybrid.
81. In computing, turning the obvious into the useful is a living
definition of the word "frustration".
-- Alan Perlis, http://www.cs.yale.edu/homes/perlis-alan/quotes.html
More information about the Python-Dev