Python Byte Code Hacking

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jul 14 03:43:37 EDT 2016


On Thursday 14 July 2016 10:14, Ian Kelly wrote:

> On Wed, Jul 13, 2016 at 12:48 PM, Vijay Kumar <vijaykumar at bravegnu.org>
> wrote:
>> Hi Everyone,
>> I wrote an article on Python byte code hacking. The article is available
>> from http://www.bravegnu.org/blog/python-byte-code-hacks.html The article
>> uses an incremental approach for explaining Python's code objects and how to
>> modify them. Unfortunately, I am stuck with Python 2, because Python 2 does
>> not optimize out the divide operation, at compile time, and my example
>> sequence depends on that behavior.
> 
> def f():
>     return g(6, 2)
> 
> def g(a, b):
>     return a // b
> 
> Now it can't optimize out the operation.


I haven't had time to read the article yet, but is Vijay talking about Python's 
peekhole optimizer? It does constant folding, so that arithmetic expressions 
containing *only* constants will compile to the result:

def f():
    return 6//2  # compiles to "return 3"


The simplest way to defeat that is to use a variable:

def f():
    x = 6
    return x//2

The peephole optimizer is simple-minded enough that it won't pre-compute that. 
Let's check:

py> import dis
py> def f(): return 6//2
... 
py> dis.dis(f)
  1           0 LOAD_CONST               3 (3)
              3 RETURN_VALUE        
py> def f():
...     x = 6
...     return x//2
... 
py> dis.dis(f)
  2           0 LOAD_CONST               1 (6)
              3 STORE_FAST               0 (x)

  3           6 LOAD_FAST                0 (x)
              9 LOAD_CONST               2 (2)
             12 BINARY_FLOOR_DIVIDE 
             13 RETURN_VALUE        



-- 
Steve




More information about the Python-list mailing list