Run Python in browser with Pyscript

Run Python in browser with Pyscript

Introduction

Python is the most Popular Programming Language out there and there are tons of reasons for that. Python is free and simple to learn. Its primary features are that it is high-level, dynamically typed, and interpreted. This makes debugging of errors easy and encourages the rapid development of application prototypes, marking itself as the language to code with. Python was developed in 1989 by Guido Van Rossum and emphasizes the DRY (Don’t Repeat Yourself) principle and readability.

For a long time, JavaScript has been the dominant language in frontend development due to its ability to run natively in the browser and interact with HTML and CSS through the DOM API. With the advent of WebAssembly, things have started to change slowly. Languages such as Go, Rust, C, C++, and many others can now run in the browser at near-native speeds, and Python hasn’t been left behind.

PyScript, created by Anaconda, is an experimental but promising new technology that makes the Python runtime available as a scripting language in WebAssembly-enabled browsers.

What is Pyscript?

Imagine a tool that makes front-end development more accessible to Python practitioners, and puts the power of Python into the hands of people that have historically focused on front-end development...

Introducing, PyScript!

  • It is an open-source web framework that allows users to create Python applications in the browser using python natively in HTML code. With PyScript, you can either embed Python code in HTML, or link to a Python file, and the code will execute in the browser without running Python in the backend.

  • PyScript was created by Anaconda and was publicly announced on April 30 at PyCon US 2022. At the time of writing, PyScript is in an alpha state and is actively being developed, so breaking changes and newer features are to be expected since it hasn’t been stably released yet.

PyScript_Watermarked.webp

Though it may sound like it's here to compete with other Javascript frameworks, it will be wrong to assume that. PyScript enables bi-directional communication between Python and Javascript objects and namespaces.

Python with Javascript

PyScript enables bi-directional communication between Python and Javascript objects and namespaces. PyScript allows you to use python logic with or without Javascript to build websites. The main benefit here is that you can leverage your existing knowledge of Python to enter the world of front-end development, lowering the entry barrier and making it more accessible

But that's not the only highlight of the project.

Key features

Community Support: Python community is pretty huge in every sector of development, and the same goes for PyScript. Post-launch, PyScript saw a huge adoption in the development sector, and in a matter of time, we shall see the strength of the community.

The Python Ecosystem: PyScript enables you to integrate various python libraries, including Pandas, NumPy, and Matplotlib.

One of the main advantages of using python is its standard library modules that solve most of the common problems that we face during software development. However, due to the constraints of a web browser and an effort to reduce the download size. Some of the modules were removed as they were irrelevant to a browser environment.

Since PyScript allows users to run code entirely on the client's web browser, you don't need a back-end server to have that code executed for you.

How Pyscript works

PyScript builds upon Pyodide, which ports CPython to WebAssembly. WebAssembly is a low-level binary format that allows you to write programs in other languages, which are then executed in the browser. With CPython in WebAssembly, we can install and run Python packages in the browser, while PyScript abstracts most of the Pyodide operations, allowing you to focus on building frontend apps with Python in the browser.

Disclaimer

Right now, PyScript is still a prototypical and experimental project. Anaconda doesn't recommend using it in production. But curious users can try out examples on the PyScript site and use the available components to build experimental Python-plus-JavaScript applications in the browser.

Ways to install PyScript

  • Download the PyScript zip file from pyscript.net, unzip the items, and use the following lines of code:
<link rel="stylesheet" href="path/to/pyscript.css" />
<script defer src="path/to/pyscript.js"></script>
  • If you don't want to install you can import the appropriate pyscript files into the tag of your HTML page like the below lines of code:
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>

Writing "Hello World"

To make the integration between Python and the web browser even more straightforward, PyScript defines several Web Components and custom elements. You can then use PyScript components on your HTML page. PyScript currently implements the following elements:

  • <py-script>: can be used to define python code that is executable within the web page. The element itself is not rendered to the page and is only used to add logic
  • <py-repl>: creates a REPL component that is rendered to the page as a code editor and allows users to write executable code.
<html>
  <head>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  </head>
  <body> <py-script> print('Hello, World!') </py-script> </body>
</html>

Adding External Modules to the application

To import modules that aren’t present in the Python standard library, you must explicitly request them by declaring their names in a<py-env> element:

<head>
      <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
      <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
      <py-env>
        - numpy
        - matplotlib
      </py-env>
</head>

The py-env tag should be added to the head tag, with a hyphen pre-pended to each package name

Python REPL

A quick and fun way to learn Python or any of its underlying libraries is by trying them out in a live interpreter session, also known as the Read-Eval-Print-Loop (REPL). By interacting with the code, you can explore what functions and classes are available and how you’re supposed to use them. It’s no different with PyScript.

Because PyScript’s environment takes a while to load, refreshing the page every time you’ve edited your code isn’t going to cut it. Fortunately, the framework comes with yet another custom element called , which allows you to execute small snippets of code without reloading the page. You can have as many of those as you like in your HTML, leaving them empty or prepopulating them with some initial Python code:

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>PyScript REPL</title>
  <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
  <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
  <py-env>
    - matplotlib
    - numpy
  </py-env>
</head>
<body>
  <py-repl>
import matplotlib.pyplot as plt
import numpy as np
  </py-repl>
  <py-repl>
def wave(frequency, amplitude=1, phase=0):
    def _wave(time):
        return amplitude * np.sin(2 * np.pi * frequency * time + phase)

    return _wave
  </py-repl>
  <py-repl></py-repl>
</body>
</html>

Conclusion

So, this is a broad overview for you to get started with PyScript. As we can see the syntax is pretty easy to understand. Web developers and Python developers can be able to understand PyScript with ease. It's still in its early phase and there will be tons of change happening. One of the goals of PyScript is to make the Web a friendly place for anyone wanting to learn to code, including kids and we hope they will be able to implement it accurately.

If you liked the article leave a heart or a thumbs up or better, both. Suggestions for any betterment of this article are highly welcome. Do let me know your reviews about this blog in the comments.