For anyone who hasn't already heard PyScript, which debuted at PyCon 2022, is a browser-embedded python environment, built on top of an existing project called Pyodide. This project, to the shock of long-term Pythonistas and web developers, seamlessly blends (well almost) JavaScript and Python in a bi-directional environment allowing developers to utilize Python staples such as NumPy or Pandas in the browser.
After playing with the project for a few days I wanted to share a few learnings and gotchya's that tripped me up on my journey to master PyScript.
Prelude: A Crash Course in PyScript
1. Package Indentation Matters!
2. Local File Access
3. DOM Manipulation
A Crash Course in PyScript
To get started using PyScript we first have to link our HTML file with the PyScript script as we would for any ordinary javascript file. Additionally, we can link the PyScript style sheet to improve usability.
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
With PyScript imported in the head of our HTML file, we can now utilize the tag in the body of our HTML to write python code.
<body>
<py-script>
for i in ["Python", "in", "html?"]:
print(i)
</py-script>
</body>
Yep! It really is just that simple to get started. Now, where do things get tricky?
Package Indentation Matters
One of the big advantages of using PyScript is the ability to import Python libraries such as NumPy or Pandas, which is first done in the Head using the tag and then inside of the tag just like you would in regular Python.
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script> <py-env>
- numpy
- pandas
</py-env>
</head><body>
<py-script>
import pandas as pd
</py-script>
</body>
On the surface, this may seem straightforward but note the indentation of the packages within .
<py-env>
- numpy
- pandas
</py-env>
Turns out that if there is any indentation you'll receive a ModuleNotFoundError: No module named 'pandas' *or*ModuleNotFoundError*: No module named 'numpy' ) *for PyScript. This error caught me off guard initially since indentation in Python is so important.
Local File Access
JavaScript handles file access very differently compared to Python... as it should given the relationship between web development and privacy and security. Hence Vanilla JavaScript does not have direct access to local files. Since the PyScript project is built on top of JavaScript your Python code won't be able to access local files like you might be used to.
PyScript does offer a solution to file access in the tag. In addition to importing packages, you can also import files such as CSVs or XLSXs.
<py-env>
- numpy
- pandas
- paths:
- /views.csv
</py-env>
Again note the indentation as in this case the CSV must be indented in relation to the paths.
With the file included in the path, you can read it within your code.
<py-script>
import pandas as pd
df = pd.read_csv("views.csv")
</py-script>
DOM Manipulation
For anyone who has worked in web development, you should be familiar with the DOM or Document Object Model. DOM Manipulation is common in most web applications as developers typically want their websites to interact with users, reading inputs and responding to button clicks. In the case of PyScript this raises an interesting question how do buttons and input fields interact with the Python code?
Again PyScript has a solution to this, however, it mightn't be what you expect. Here are a few (of many) examples where PyScript has functionality:
- For buttons, you can include pys-onClick="your_function" parameter to trigger python functions when clicked.
- For retrieving user input from within the tag *document.getElementById('input_obj_id').value *can retrieve the input value.
- And Finally pyscript.write("output_obj_id", data) *can write output to a tag from within the * tag.
We can see these three DOM manipulation techniques put together into one web application that lets users check if a CSV has been added to the PyScript path:
<body>
<form onsubmit = 'return false'>
<label for="fpath">filepath</label>
<input type="text" id="fpath" name="filepath" placeholder="Your name..">
<input pys-onClick="onSub" type="submit" id="btn-form" value="submit">
</form><div id="outp"></div> <py-script>
import pandas as pd def onSub(*args, **kwargs):
file_path = document.getElementById('fpath').value
df = pd.read_csv(file_path)
pyscript.write("outp",df.head())
</py-script>
</body>
These examples aren't comprehensive as the project also supports visual component tags.
Conclusion
PyScript is a wonderful step in the right direction for bringing some excellent Python packages into the web development space. With that said it still has a bit of growing to do and there are many improvements that need to be made before the project sees widespread adoption.
Show some support to the team working on this awesome project: https://github.com/pyscript
Leave a comment with any other insights or gotchya's that you might have experienced working with PyScript and I'll make a part 2.
Top comments (3)
Great points its an exciting time to be a Python developer.
Do you have any exciting project ideas @andrewbaisden?
I have 100+
50 Cool Web And Mobile Project Ideas for 2021
50 Cool Web And Mobile Project Ideas for 2022