Bringing Python to Browser!

 

Jupyter notebook has always been a de-facto choice when you teach the Python programming language or while developing prototype machine learning models or doing exploratory data analysis. The reasons are manifold. The most important reason is due to its ability to interleave the rich set of explanatory notes using markdown cells and the code cells (for this reason, it is also called a computational document).

This unique feature makes learning python components coherently (i.e., no switching back and forth between explanatory notes and IDE). However, suppose that someone visits your site to learn python. What can we do then?. Well, we can convert the entire notebook into a markdown/HTML file and publish it on the site. Well, the published page will look neat as shown below. There, we can copy the code,read the notes, but...

as you guessed, we can't execute the statements in the code cells!.Why?...

Simply because it requires a local or a web server to execute the code cells in the notebook. Therefore, we need to open Google colab for quick experimentation by copying codes in the notebook. It offers a free server with pre-installed python packages such as NumPy,matplotloib,scikit-learn and many more. Imagine, What if Python runs in the site itself without requiring any remote server . That will be cool!.

That's where PyScript helps us!.How can we do it?.Just add the single line of code (line:6) in the <head> section.

and enclose the python code inside the custom HTML elements <py-script> or <py-repl> in the <body> section. That's all!. We are ready to go ahead and execute python codes in the browser.Ok! without further ado..let's see some examples
Reminding you once again: The following code cells are not running in any remote server, they are simply running in the browser!.

1.Displaying Hello world:

print("Hello world")

Now, it is clear that we can insert any valid python statements in the cell and it gets executed. Let's do more..

2. Calling a function:

def factorial(n): if n==0: return 1 return n*factorial(n-1) print(factorial(8))

So far so good!. Let's create objects to represent points in 2D cartesian coordinate. Also, implement methods to compute the distance from the origin to the point. This requires sqrt() function to be imported from the math module. Can we import standard built-in modules?. Let's see

3.Creating Objects and importing modules:

import math class Point(object): def __init__(self,x,y): self.x = x self.y = y def dist_from_origin(self): ''' Calculate the Euclidean distance from the origin to the point ''' return math.sqrt(self.x**2+self.y**2) p = Point(3,4) print("Distance from the origin is: ",p.dist_from_origin())

It works as expected!. Well, this implies that we can import all standard modules that come with python.This is great!.

Power to python comes from its large collection (around 100K) of third-party packages that supports variety of tasks. For tasks related to data science, we need packages for numerical computation and data visualization. Therefore, it would be super cool if we are able to use packages like numpy and matplotlib . Fortunately, PyScript offers a custom HTML element <py-env> to import required packages (you can check the list of packages supported here) . Let's execute the following cell,

4. Numerical Computation

- numpy - matplotlib import numpy as np A = np.array([[1,1],[1,-1]]) b = np.array([[1.5,-2]]) x = np.linalg.inv(A)*b print(x)
 

Wow!..NumPy on the browser!.Let's check the final requirement, that is, data visualization.

5.Plotting waves

import numpy as np from matplotlib import pyplot as plt x = np.linspace(0,1,100) y0 = np.sin(2*np.pi*x) y1 = 0.5*np.sin(6*np.pi*x) y2 = 0.25*np.sin(10*np.pi*x) y3 = 0.125*np.sin(14*np.pi*x) fig,(ax0,ax1) = plt.subplots(2,1) ax0.plot(x,y0+y1+y2+y3) ax0.set(xlabel='x',xlim=(0,1),ylim=(-1.1,1.1),title='Signal and its harmonics') ax0.grid(True) ax1.plot(x,y0) ax1.plot(x,y1) ax1.plot(x,y3) ax1.plot(x,y3) ax1.set(xlabel='x',xlim=(0,1),ylim=(-1.1,1.1)) ax1.grid(True) fig

Despite PyScript's nascent stage, what it offers is laudable. Just by knowing a bit of HTML and JavaScript , you can create more useful stuffs in your site with the help of PyScript .Moreover, it comes with eight custom HTML elements to create buttons, input-boxes, widgets and so on. I have just used only two of them, <py-repl> and <py-env> in this article. Currently, it is under a rapid development, so we can expect a lot of changes in the near future.You can read a lot about how it works under the hood by refering the following resources

.

Resources:

  1. Presentation on what is Iodide and Pyodide (on top of which the PyScript is built).
  2. Pyodide official page.
  3. A list of PyScript demos.