[Python-ideas] Bytecode for calling function with keyword arguments

Serhiy Storchaka storchaka at gmail.com
Thu Apr 21 11:52:56 EDT 2016

Currently the call of function with keyword arguments (say `f(a, b, x=c, 
y=d)`) is compiled to following bytecode:

       0 LOAD_NAME                0 (f)
       3 LOAD_NAME                1 (a)
       6 LOAD_NAME                2 (b)
       9 LOAD_CONST               0 ('x')
      12 LOAD_NAME                3 (c)
      15 LOAD_CONST               1 ('y')
      18 LOAD_NAME                4 (d)
      21 CALL_FUNCTION          514 (2 positional, 2 keyword pair)

For every positional argument its value is pushed on the stack, and for 
every keyword argument its name and its value are pushed on the stack. 
But keyword arguments are always constant strings! We can reorder the 
stack, and push keyword argument values and names separately. And we can 
save all keyword argument names for this call in a constant tuple and 
load it by one bytecode command.

       0 LOAD_NAME                0 (f)
       3 LOAD_NAME                1 (a)
       6 LOAD_NAME                2 (b)
       9 LOAD_NAME                3 (c)
      12 LOAD_NAME                4 (d)
      15 LOAD_CONST               0 (('x', 'y'))
      18 CALL_FUNCTION2           2


1. We save one command for every keyword parameter after the first. This 
saves bytecode size and execution time.

2. Since the number of keyword arguments is obtained from tuple's size, 
new CALL_FUNCTION opcode needs only the number of positional arguments. 
It's argument is simpler and needs less bits (important for wordcode).


1. Increases the number of constants.

More information about the Python-ideas mailing list