PyScript: Best Practices

Written by

With the compatibility of running Javascript libraries, if you are a data scientist or backend developer using Python, you can now easily deploy code on the frontend side, and it is expected that it will be available for more programming languages in the future.

This blog post explores PyScript, a new technology recently released by Anaconda that enables developers to run Python code and popular libraries on web browsers, and best practices when using it.

PyScript was created with the idea of making it web-friendly and enabling the capacity of Python developers to generate interesting and interactive applications. Their developers expect to combine multiple open frameworks to provide a way to create sophisticated applications rather than focusing on making them accessible to all.

What is possible with PyScript?

After taking a look at the documentation and the repository base available (PyScript webpage, PyScript Repository), it is important to understand that it is based on Pyodide and WASM (Web Assembly). There is nothing new, but it generates a lot of curiosity about how Python can run as JavaScript just using an interpreter.

It is required to add the file to the web server or use the CDN. It is also suggested to add the CSS file:

<link rel=" stylesheet" href="https://PyScript.net/alpha/PyScript.css" />
<script defer src="https://PyScript.net/alpha/PyScript.js"></script>

When a new webpage loads, it will take a few seconds to be ready for the end-user, depending on user machine resources. Maybe in the future, the interpreter can be included in the web browser to get better performance, as it is now for JavaScript.

For developers, it can be helpful to install the VS Code extension. It provides more than 200 snippets for PyScript, Django Template, Python, and HTML and provides code highlighting for the Python language in PyScript in HTML files. 

The project includes all the standard libraries in Python. However, most of the most used libraries in data science are available. Some of them are Numpy, Pandas, and Mathplot. Adding libraries available in the Python package manager will give an error as not found or not recognized class. Another way that could be possible is to make a connection with JavaScript libraries. For further information on how to get these libraries, you can take a look at the example handtracker in the official repository. It shows how it is possible to import some functions and run them inside Python code. 

Import a JS function, for example:

<py-script>
     from js import handTrack, requestAnimationFrame
     from pyodide import create_once_callable
     import asyncio
//Calling handTrack function wrote in JavaScript 
def toggle_video(evt):
  global isVideo
  if (not isVideo):
    update_note.write("Starting video")
    PyScript.run_until_complete(start_video())
  else:
    update_note.write("Stopping video")
    handTrack.stopVideo(video.element)
    isVideo = False
    update_note.write("Video stopped")

Don’t forget to include the JS script in the HTML file: 

 <script src="lib/handtrack.min.js"> </script>

As it is possible to import JavaScript files, it can also be possible to import them easily.

When developers are working on training models for data science, Python notebooks are the most used. We talk about Jupyter or Ipython. The client asks for some examples. Sending the notebook and giving them a preview is always a hard task to complete. Using the model and transforming the outputs into images or web pages may not meet the client's expectations, and it may lose possible interaction with the model. One of the best features of PyScript is the plot model for the end-user.

Is it time to replace JavaScript? 

PyScript is a newly released technology. It cannot simply replace JavaScript. It can help Python developers work with the DOM directly, but remember that JavaScript has been in the lead for a long time on the frontend side.

PyScript best practices

  • The first suggestion is to take advantage of the VSCode extension called PyScript. Based on my experience, snippets can be a great help to keep the code in the same style and have cohesion between multiple files. 
  • This technology was thought to generate Python widgets and components, trying to make them reusable for other developers. In this way, keep the code blocks as reusables, keeping in mind that the code will not only be used by you in the future. It can be part of a bigger project or used by new developers. Keep it simple and don't forget to document the code; PyScript provides ways to import files and decouple the code into small and smart files.
  • If it is read by a new developer to get knowledge about code repositories, it keeps the code safe and always updated with the version available to show. A new repository is mandatory to track the history and code progress of a new project.. At the moment of writing this blog, there is no present library to test PyScript COD. Unit testing for Python files and using a frontend solution to ensure the code is doing what it is supposed to do could be an option.
  • In terms of front-end performance, try to optimize the files imported, reduce and minify the resources used in the webpage, and also implement lazy loading. When the webpage is called, the required content is loaded first, and the remaining content will be loaded when the user requires it.
  • To keep the code easy to find in the folder structure, the proposal is to separate by features or modules using the same name in the HTML file and a folder to organize the scripts and help another developer to find obvious and simple features and separate files between the js and python folders.

Conclusion

PyScript shows great potential as a technology and is easy to use. However, as mentioned before, it cannot replace JavaScript as the most used language in the frontend. But it can be an opportunity to get the best performance in plots, machine learning outputs, and other use cases. 

Frequently Asked Questions