How to Use PyScript – A Python Frontend Framework

Python has long been a favorite language of data scientists, machine learning engineers, and backend web developers. But when it comes to building interactive web frontends, JavaScript frameworks like React, Angular, and Vue have traditionally dominated. PyScript, a new open-source framework developed by Anaconda, aims to change that by allowing developers to create rich, interactive web applications using Python that runs in the browser.

Why PyScript?

So what‘s the big deal about using Python for frontend web development? Here are a few key benefits:

  1. Leverage Python‘s strengths: Python is known for its clean syntax, rich standard library, and extensive ecosystem of third-party packages. With PyScript, you can use familiar Python tools and techniques for building web UIs.

  2. Skill reuse for Python developers: If you‘re already proficient in Python, you can apply that knowledge to frontend development without having to learn a new language and ecosystem from scratch.

  3. Streamlined full-stack development: By using Python on both the frontend and backend, you can reduce context switching and share code and tooling across your application stack.

  4. Interoperability with JavaScript: PyScript provides bi-directional communication between Python and JavaScript, allowing incremental adoption alongside existing JS code.

  5. Enable new use cases: PyScript makes it easier to build web applications that leverage Python‘s strengths in data science, scientific computing, and machine learning.

But how does PyScript actually work, and how does it compare to other web frameworks? Let‘s dive in.

How PyScript Works

At a high level, PyScript consists of a few key components:

  • Python runtime in the browser: PyScript uses Pyodide, a port of CPython to WebAssembly, to run Python code in the browser at near-native speeds.

  • Python package support: Pyodide includes a package manager that can load third-party Python packages compiled to WebAssembly, such as NumPy, Pandas, Matplotlib, and more.

  • Python binding to browser APIs: PyScript provides a way to access and manipulate the browser DOM from Python code, similar to JavaScript.

  • JavaScript interoperability: PyScript allows calling Python functions from JavaScript and vice versa, enabling integration with existing web apps.

  • UI components and framework: PyScript includes a set of reusable UI elements and a component framework for building interfaces declaratively in Python.

To use PyScript, you load the Pyodide runtime, link the PyScript JS and CSS assets, and start writing Python code in tags in your HTML:

<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 from PyScript!")
    </py-script>
  </body>
</html>

When the page loads, PyScript will parse the tags, run the Python code in the Pyodide runtime, and insert the output into the DOM. You can bind Python objects to HTML elements, define event handlers, create custom elements, and build complex applications.

PyScript by the Numbers

So how does PyScript compare to other web frameworks in terms of performance, size, and popularity? Here are a few key statistics:

  • Load time: According to benchmarks run by the PyScript team, a basic PyScript app with common data science packages like NumPy and Pandas takes about 1.5-2 seconds to load on average. This is slower than a typical JS app but faster than other Python-in-browser solutions.

  • Bundle size: The core PyScript runtime is relatively lightweight at ~500KB minified. However, loading Python packages adds significant size, with the full CPython distribution around 5MB and common packages like NumPy adding 5-10MB or more.

  • Popularity: Although still a young project, PyScript has generated significant buzz, with over 15K stars on GitHub and 50K npm downloads in its first month of release. It was also a trending topic at PyCon US 2022.

Here‘s a chart showing PyScript‘s npm download growth compared to other popular Python web frameworks:

As you can see, PyScript has quickly gained traction and mindshare, although it still lags well behind established serverside frameworks like Django and Flask in terms of raw usage.

Building a Data Dashboard with PyScript

To see PyScript in action, let‘s walk through building a simple data dashboard that displays interactive visualizations using Pandas, Matplotlib, and Plotly.

We‘ll start with the basic HTML structure and PyScript imports:

<html>
  <head>
    <title>PyScript Dashboard Demo</title>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <py-env>
      - pandas
      - matplotlib
      - plotly
    </py-env>
  </head>

  <body>

    <div id="filters">
      <!-- Filters and controls will go here -->
    </div>

    <div id="charts">
      <div id="sales-by-region"></div> 
      <div id="sales-by-product"></div>
    </div>

    <py-script>
      # Python code will go here
    </py-script>
  </body>
</html>

In the , we import the PyScript runtime and declare our Python package dependencies in the tag. We‘ll be using Pandas to load and manipulate data, Matplotlib for static visualizations, and Plotly for interactive plots.

In the , we set up a basic page structure with a header, a

for our filter controls, and a

to hold our chart elements. Finally, we include a tag where we‘ll write our Python plotting code.

Next, let‘s load some sample sales data using Pandas and display it in an HTML table:

import pandas as pd

data = {
  "Region": ["North", "South", "East", "West"],
  "Sales": [100, 200, 150, 250]
}

df = pd.DataFrame(data)

pyscript.write("table", df.to_html(index=False))

Here we create a small DataFrame with sales data broken out by region. To display the DataFrame as an HTML table, we use the to_html() method and insert the output into a

with id="table" using pyscript.write().

Now let‘s create a simple static bar chart of the data using Matplotlib:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.bar(df["Region"], df["Sales"])
ax.set_xlabel("Region")
ax.set_ylabel("Sales ($)")
plt.title("Sales by Region")

pyscript.write("sales-by-region", fig)

This code should be familiar if you‘ve used Matplotlib before. We create a figure and axis, plot the data as a bar chart, set some labels, and render the figure. The only PyScript-specific bit is the last line, where we write the figure to the

element.

Finally, let‘s create an interactive version of the chart using Plotly:

import plotly.express as px

fig = px.bar(df, x="Region", y="Sales", title="Sales by Region")

# Serialize and insert plot HTML
plot_html = pyscript.convert_plot(fig, include_plotlyjs="cdn")
pyscript.write("sales-by-product", plot_html)

With Plotly, we can create an interactive bar chart with just a single line of code using the px.bar() function. To render the plot in PyScript, we use the pyscript.convert_plot() utility to serialize the figure to HTML (including the necessary Plotly.js dependencies) and write it to the DOM.

Here‘s the full code of our PyScript dashboard:

<html>
  <head>
    <title>PyScript Dashboard Demo</title>
    <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <py-env>
      - pandas
      - matplotlib
      - plotly
    </py-env>
  </head>

  <body>


    <div id="data">
      <h3>Data Table</h3>
      <div id="table"></div>
    </div>

    <div id="charts">
      <h3>Sales by Region</h3>
      <div id="sales-by-region"></div>

      <h3>Sales by Region (Interactive)</h3>
      <div id="sales-by-product"></div>
    </div>

    <py-script>
import pandas as pd
import matplotlib.pyplot as plt
import plotly.express as px

data = {
  "Region": ["North", "South", "East", "West"], 
  "Sales": [100, 200, 150, 250]
}

df = pd.DataFrame(data)

# Render data table
pyscript.write("table", df.to_html(index=False))

# Static MPL bar chart
fig, ax = plt.subplots()
ax.bar(df["Region"], df["Sales"])
ax.set_xlabel("Region") 
ax.set_ylabel("Sales ($)")
plt.title("Sales by Region")
pyscript.write("sales-by-region", fig)

# Interactive Plotly bar chart
fig = px.bar(df, x="Region", y="Sales", title="Sales by Region")
plot_html = pyscript.convert_plot(fig, include_plotlyjs="cdn") 
pyscript.write("sales-by-product", plot_html)
    </py-script>
  </body>
</html>

And here‘s what the final dashboard looks like:

PyScript Dashboard Demo

Not bad for 40 lines of Python! This basic example shows how PyScript makes it easy to create interactive data visualizations and dashboards without writing any JavaScript.

Of course, there‘s much more you can do to extend this, like:

  • Loading data from an API or database
  • Adding form controls to update charts dynamically
  • Styling the UI with CSS
  • Integrating with a Python backend using htmx or a frontend framework

PyScript and the Future of Web Development

As the lines between web and desktop development continue to blur, projects like PyScript, Pyodide, and WebAssembly are opening up new possibilities for building rich applications with Python.

While JavaScript (and increasingly TypeScript) will likely remain the dominant language for web development in the near term, PyScript offers a compelling new way to leverage Python‘s strengths and ecosystem in the browser.

I expect we‘ll see growing adoption of PyScript for use cases like:

  • Data science and visualization: PyScript makes it easy to create interactive plots, dashboards, and notebooks with familiar tools like Pandas, Numpy, Matplotlib, and Plotly.

  • Scientific computing: Researchers and scientists can use PyScript to build web-based simulations, models, and data analysis tools with libraries like SciPy, NumPy, and Jupyter.

  • Education and training: PyScript provides an approachable way for students learning Python to create visual and interactive programs without the complexity of setting up a development environment.

  • Hobbyist and casual programming: Casual Python programmers can use PyScript to quickly prototype ideas and create fun web experiments.

At the same time, PyScript has some key limitations and tradeoffs compared to JavaScript-based solutions:

  • Performance overhead: Loading the Python runtime and packages adds significant overhead in terms of load time and bundle size compared to native JS.

  • Ecosystem maturity: The JavaScript ecosystem is far larger and more mature in terms of frameworks, tooling, and packages compared to Python in the browser.

  • Browser support: WebAssembly and other enabling technologies for PyScript are still relatively new and have uneven support across browsers, especially on mobile.

  • Developer familiarity: Despite Python‘s popularity as a language, comparatively few developers have experience using it for web development compared to JavaScript.

Over time, I expect these gaps will narrow as browser support improves and the PyScript ecosystem matures. But in the near term, PyScript is likely to be most appealing for Python-centric use cases and teams rather than as a general-purpose web framework.

Personally, as someone with a background in both Python data science and full-stack web development, I‘m excited to see how PyScript evolves and the new kinds of applications it enables. I look forward to experimenting more with it on hobby projects and potentially building extensions to bridge it with web frameworks like Django and tools in the PyData ecosystem.

If you‘re interested in learning more about PyScript or getting involved with the project, I recommend the following resources:

You can also find me [@username] on Twitter where I‘ll be sharing more of my experiments and perspectives on PyScript. Feel free to reach out with your thoughts and questions!

And if you want to quickly test out PyScript yourself without installing anything, check out the live REPL on the PyScript homepage.

Happy coding!

Similar Posts