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

Cesare Di Mauro cesare.di.mauro at gmail.com
Sun May 15 09:51:58 EDT 2016


With WPython I've solved this scenario with only a new opcode, LOAD_CONSTS,
which basically unpacks the (constant) tuple into the stack.

So, you don't need new opcodes for new function calls, and LOAD_CONSTS is
only used when needed.

Regards,
Cesare

2016-04-21 17:52 GMT+02:00 Serhiy Storchaka <storchaka at gmail.com>:

> 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
>
> Benefits:
>
> 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).
>
> Disadvantages:
>
> 1. Increases the number of constants.
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160515/5ddd59e7/attachment.html>


More information about the Python-ideas mailing list