[Python-ideas] Add specialized bytecode with guards to functions

Scott Sanderson scoutoss at gmail.com
Wed Oct 21 20:36:30 CEST 2015


>
> It could just as easily be something like 
>
> def foo(): 
>    return _1(abc) 
>
> foo = add_consts(foo, {'_1':len}) 
>

You can actually do this already in pure Python.  We implemented almost 
exactly what's proposed here as the asconstants 
<https://github.com/llllllllll/codetransformer#asconstants> decorator in 
codetransformer <https://github.com/llllllllll/codetransformer>:

>>> from codetransformer.transformers import asconstants
>>> @asconstants(a=1)
>>> def f():
...     return a
...
>>> f()
1
>>> a = 5
>>> f()
1


This works by making two changes to the function's __code__:

1. We add an entry to foo.__code__.co_consts.
2. We rewrite all LOAD_{GLOBAL|NAME} bytecode instructions of that name to 
be LOAD_CONSTs instead.

This makes the function itself slightly faster, since LOAD_CONST is 
generally faster than other loads.  But more importantly, it statically 
freezes the value of a particular name in the function, which makes it 
possible/sane to implement other more interesting 
transformations/optimizations.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151021/a9e4b0e9/attachment-0001.html>


More information about the Python-ideas mailing list