Friday, June 6, 2014

optional static typing

People have been asking for optional types for Python for at least 10 years, and only recently have a couple of good solutions appeared, one is MyPy by Jukka Lehtosalo, but the github project hasn't been updated in several months, and no recent updates on the dev blog either. Python could greatly benefit from optional typing, it makes your code more clear and readable, can provide better compile or time checks, and better performance.

The above benchmark shows PythonJS in normal mode with statically typed variables is 20 times faster compared to below without statically typed variables.

Most of the performance gain comes from typing the arr variable as list, this allows the translator to bypass a runtime method lookup and instead directly call arr.push.

new syntax

def f(arr, x):
  list arr
  int x
  int y = somefunction()
  arr.append( x+y )

PythonJS allows you to type each variable in a function body as a plain statement int x or in an assignment expression int z = somefunction(). This is different from the approach of MyPy where things can only be typed in the function's annotations. It is implemented as a simple text pre-processor, for the details see here, and source code here. This is still a very new feature and can only optimize a few cases. In the future it can be leveraged to further increase performance, and provide translation-time error checking.


  1. Just out of curiosity, why didn't you used the python 3's function annotations ?


    def F(i:'int', n, arr:'list'):
    while i < n:

  2. I started with this current solution because it allows typing of any variable within the function body, and not just the function arguments.

    In the future I will try to support Python3's function annotations for typing, either by making the translator compatible with Python3 and using the AST parser, or directly parsing the annotations in the pre-processing phase.