[Python-Dev] Why is Bytecode the way it is?
Paul Prescod
paul at prescod.net
Thu Jul 8 07:27:04 CEST 2004
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).
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.
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.
Paul Prescod
More information about the Python-Dev
mailing list