Total Pageviews

Saturday, 15 February 2014

PythonJS

PythonJS is a Python to Javascript translator written in Python, created by Amirouche Boubekki and Brett Hartshorn, currently maintained and developed by Brett. It features: list comprehensions, classes, multiple inheritance, operator overloading, function and class decorators, generator functions, HTML DOM, and easily integrates with JavaScript and external JavaScript libraries. The generated code works in the Browser and in NodeJS. Note: the Dart, CoffeeScript and Lua backends are still very experimental.

Speed

PythonJS allows you to select which features you need for each section of your code, where you need performance you can disable operator overloading, and other slow operations. Features can be switched off and on for blocks of code using pythonjs.configure() or the special with statements and decorators described below. When PythonJS is run in fastest mode (javascript mode) it beats PyPy in the Richards, and N-Body benchmarks.
N-Body benchmark, PythonJS in javascript mode has similar performance to Dart.

translator.py

To convert your python script into javascript use translator.py located in the "pythonjs" directory. You can give it a list of python files to translate at once. It will output the translation to stdout. The default output type is JavaScript.
Usage:
translator.py [--dart|--coffee] file.py
Example:
cd PythonJS
pythonjs/translator.py --coffee myscript.py > myscript.coffee

NodeJS

Using PythonJS you can quickly port your server side code to using NodeJS. If you are using Tornado, porting is even simpler because we have written a compatibility layer that emulates the Tornado API and hides the NodeJS internal modules.

How does it work?

Translation to JavaScript is done in two steps:
+------------+    +-----------------+    +------------+
¦ .py source ¦--->¦ pythonjs subset ¦--->¦ .js source ¦
+------------+    +-----------------+    +------------+
First, the script walks the AST tree of Python source and translates it into the subset of Python called pythonjs. This reduced subset is still valid Python code, and its AST gets parsed again in the second translation phase that converts it into final JavaScript form.

from  https://github.com/PythonJS/PythonJS