1. Victor Stinner
  2. astoptimizer


astoptimizer /

Filename Size Date modified Message
1.5 KB
2.8 KB
920 B
187 B
1.9 KB

AST Optimizer

Experimental AST optimizer for Python.


By default, the optimizer only enables portable optimizations. If you control your environment (platform, Python command line options, environment variables), you can enable more optimizations using the Config() class.

Example enabling optimization for a specific platform and a specific Python version:

def optimize_ast(tree):
    config = Config('platform', 'pythonenv')
    return Optimizer(config).visit(tree)

Configuration features:

  • "builtins": enable optimization on builtin functions (option always enabled)
  • "pythonenv": optimizations specific to the running Python executable. Don't enable these optimizations if you don't control the Python version, command line arguments and environment variables.
  • "platform": optimizations specific to a platform.



from astoptimizer import parse_ast, Optimizer
tree = parse_ast('print(1+1'))
tree = Optimizer(config).visit(tree)
code = compile(tree, "<ast>", "exec")
exec(code)  # or exec code with Python 2

See also demo.py script.


Version 0.1 (2012-08-12)

  • First public version (to reserve the name on PyPI!)


  • move invariant out of the loop: x=[0]; for ...: x.append(...)
  • unroll loop
  • infer type
  • support "from sys import platform"
  • x=[1, 2, 3]; y=x[1]
  • "x=[]; for item in data: x.append(item.upper())" => "x=[item.upper() for item in data]" ?
  • replace "range" with "xrange" when used in a loop?
  • sys.version_info >= (3,3)
  • sys.version_info.major == 2
  • (x * 2) * 3 => x * 6, "fast-math" option?
  • python 2.5 compatibility?