2024-04-06 pyscript.net Python in the browser

Using Python in the browser

PyScript lets you use your favorite Python libraries on client-side web pages.

While there are some great Python web server frameworks such as Flask, Django, and Bottle, using Python on the server side adds complexity for web developers.

To use Python on the web, you also need to support JavaScript on client-side web pages. To address this problem, some Python-to-JavaScript translators, such as JavaScripthon, Js2Py, and Transcrypt, have been developed.

The Brython (which stands for Browser Python) project [1] took the first big step in offering Python as an alternative to JavaScript by offering a Python interpreter written in JavaScript. Brython is a great solution for Python enthusiasts, because it’s fast and easy to use. However, it only supports a very limited selection of Python libraries.

PyScript [2] offers a new, innovative solution to the Python-on-a-web-page problem by allowing access to many of the Python Package Index (PyPI) repository libraries. The concept behind PyScript is a little different. It uses Pyodide, which is a Python interpreter for the WebAssembly (Wasm) virtual machine. This approach offers Python within a virtual environment on the web client.

In this article, I will introduce PyScript with some typical high school or university engineering examples. I will also summarize some of the strengths and weakness that I’ve found while working with PyScript.

Getting Started

PyScript doesn’t require any special software on either the server or client; all the coding is done directly on the web page. For PyScript to run, it needs three things (Figure 1):

  • a definition in the header for the PyScript CSS and JS links,

  • a <py-config> section to define the Python packages to load, and

  • a <py-script> section for the Python code.

Summary

Using Python libraries such as pandas, SymPy, or Matplotlib on a client page can be a very useful feature. It’s also nice that these PyScript pages don’t require Python on the client machine.

While working with PyScript, I found two issues. The call-up is very slow (especially compared to Brython pages).

In addition, I often got tripped up with Python indentation when I was cutting and pasting code. Overall, however, I was very impressed with PyScript, and I look forward to seeing where the project goes.