Press "Enter" to skip to content

How to convert Python to JavaScript (and back again)

Python or JavaScript? While we are still arguing over who has the upper hand or the brighter future, there is little doubt as to who owns the front end of the web. Until WebAssembly progresses to the point where we can transparently compile other languages ​​for use in the browser, it’s JavaScript in the browser or nothing.

well maybe not nothing. JavaScript is the favorite target language for “transpilers” who convert one programming language to another (see: TypeScript, Emscripten, Cheerp, Cor). And Python’s large following and sheer number of libraries available make it an excellent candidate to be converted, i.e., transpiled, into JavaScript.

Here are seven current projects to make Python useful in the world of JavaScript. It stands out for being able to convert in both directions.

British

One of the promises that WebAssembly makes is to allow us to use whatever language we choose to develop for the web, although this remains a distant goal. The philosophy behind Brython, at least as far as Python 3 is concerned, is why wait?

Brython implements a version of Python 3 for client-side web programming through a JavaScript library that emulates all of the keywords and most of the built-in functions of Python 3. Scripts written in Python can be included directly in a Web page. Brython provides a high-level Python module interface (the browser package) to interact with the DOM (Document Object Model) and the browser, handling all the work that is normally done directly in JavaScript.

Lots of live code examples and a gallery of applets demonstrate how it all works. It is even possible to use Brython to write a native Android app in Python. Asynchronous functionality is available, although you must use Brython’s async module instead of python asyncio.

Brython does not escape the restrictions placed on JavaScript in the browser. For example, there is no support for dealing with the local file system. However, there is support for using HTML5 local storage, if all you need is some way to persist data on a per-application basis.

javascripthon

JavaScripthon strictly focuses on translating Python 3.5 and later code into JavaScript, without trying to provide full in-browser support as in projects like Brython. It outputs ES6 code to minimize the need for polyfills on the browser side and works well with tools like Webpack by preserving source maps.

Most common Python keywords and behaviors are supported, including async and await, Python 3.6 f-strings, and Python class methods and inheritance. You can also insert JavaScript inline via a special function call, if you ever need to display JavaScript directly.

Note that the last commits for the JavaScripthon project were in July 2022, although it was updated to support Python 3.10 as its latest version.

Instant

Jiphy’s name is short for “JavaScript in, Python out”. In other words, Jiphy converts in both directions between the two languages. Also, code from both languages ​​can be mixed before being converted to either target language.

Before you dive in and start converting all of OpenStack to JavaScript, pay attention: Jiphy is not a full codebase conversion. Rather, its role is, as the README says, “to reduce the context switching required for a Python developer to write JavaScript code and vice versa.”

Jiphy’s biggest drawback is that it only supports a subset of Python’s features. Default classes and arguments are not available, although decorators and exceptions are supported. Much of this is because Jiphy strives for a line-to-line relationship between source code and target code. To that end, there is no support for mapping the Python standard library to JavaScript constructs.

Please note that the Jiphy project has not been updated since mid-2020. Jiphy should be considered strictly experimental until work resumes.

JS2Py

JS2Py converts JavaScript to Python, as the name implies, using a pure Python conversion engine. It has official support only for ES5 at the moment, although there is experimental ES6 support for the brave and bold.

Also Read:  Intro to tRCP: Integrated, full-stack TypeScript

JS2Py supports a lot of cross-interoperation between Python and JavaScript. You can import existing Node.js modules into your Python code, via a js2py.require method. JavaScript-side variables can be evaluated on the Python side, and Python objects can also be used from JavaScript code.

JS2Py also includes a highly experimental virtual machine that evaluates Python JavaScript code, but it is not yet recommended for production use.

rapiddscript

RapydScript “allows you to write your JavaScript application in a language much closer to Python without the overhead that other similar frameworks present.” The project is similar to CoffeeScript in that it ingests code written in an alternate language, in this case a version of Python, and generates JavaScript that can be executed anywhere as-is.

Therefore, RapydScript offers the best of both worlds, bringing clean Python syntax to JavaScript capabilities like anonymous functions, DOM manipulation, and the ability to leverage JavaScript libraries like jQuery or Node.js. That’s right, you can use Rapydscript-generated code to power web pages or Node.

Another convenient feature of RapydScrypt: it offers Python and JavaScript naming for operations where possible. For example, him $ special symbol used by jQuery works as is in RapydScript, and arrays can support both the .push (JavaScript) and .append (Python) methods. However, the project has not been updated since May 2021, so it should be considered experimental.

PyScript

Like Brython, which uses some of the same underlying technology, PyScript allows Python to run directly in the browser. PyScript uses the Pyodide project, a Python runtime ported to WebAssembly, to make the browser a more hospitable environment for running Python as a web scripting language.

PyScript allows bi-directional communication between the JavaScript and Python environments. For example, Python scripts can work with the document’s object model, invoke JavaScript code, and work with the results it returns. But Python applications can also use the browser as an output device. For example, the python print() The command can be used to write output directly to a web page, the same way you would print output to the console.

PyScript also provides ways to work with packages available in the PyPI Package Index, although not all of them may behave as expected. For example, PyScript still doesn’t work with the requests library or other Python tools for working with HTTP requests. However, PyScript provides wrappers for JavaScript. fetch method to perform the same tasks.

transcribe

If you hear the name Transcrypt and think of TypeScript, you’re not too far off the mark. Transcrypt follows the same basic idea: transpile Python to JavaScript. It also tries to preserve, whenever possible, the structure and idioms of the original Python code, including constructs like lambdas and multiple inheritance between classes.

Additionally, source maps can be generated for transpiled code that point to the original Python, so that developers can debug using that code instead of the generated JavaScript. According to the documentation, Transcrypt accomplishes these tasks with CPython’s Abstract Syntax Tree module, which allows programmatic access to the way Python parses its own code.

One of the biggest advantages of Transcrypt is the automatic access to the document object model. If you try to access document.getElementById in Python, for example, the converted code will use the document.getElementById in javascript. For programmers who want to use frameworks to perform DOM manipulation, an online book provides step-by-step tutorials for using Transcrypt to write JavaScript applications using the React and Material-UI libraries.

A partner project, and still under wraps, is Numscrypt, which ports NumPy’s math and statistics library into JavaScript. So far, Numscrypt provides only a subset of NumPy’s functions, although these functions (for example, matrix math) are among the most widely used. However, Numscrypt hasn’t been updated since 2021.

Copyright © 2023 IDG Communications, Inc.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *