Compile python source without constant folding optimization

219 views Asked by At

I have a python snippet as follows

5 + 6 * 8

Compiling this to AST gives:

>>> ast.dump(compile('5+6*8', '', 'eval', ast.PyCF_ONLY_AST))    
Expression(body=BinOp(left=Num(n=5), op=Add(), right=BinOp(left=Num(n=6), op=Mult(), right=Num(n=8))))

Note that in the generated AST 6 * 8 is not optimized into 48.

However, if I compile this generated AST and disassemble, 6 * 8 is replaced by 48.

>>> astree = compile('5+6*8', '', 'eval', ast.PyCF_ONLY_AST)
>>> dis.disco(compile(astree, '', 'eval'))
  1           0 LOAD_CONST               0 (5)
              3 LOAD_CONST               3 (48)
              6 BINARY_ADD          
              7 RETURN_VALUE 

My question

How to compile the code to bytecode without the constant folding optimization? I need to do this for developing an obfuscator.

0

There are 0 answers