Today I learned how to use JavaScript functions in PyScript.
In case you missed, yesterday I learned about PyScript, a tool that allows you to use Python inside your HTML! In other words, PyScript enables you to run Python on the client side.
In order to use JavaScript functions in PyScript, you can import them from the available js
module.
For example, to use console.log
from within PyScript, you just type from js import console
in your PyScript tag.
Then, you can call console.log
regularly:
<py-script>
from js import console
console.log("Hey there, from 'console.log' inside PyScript!")
</py-script>
If you include that in one of your pages and then check the console,
you will find the message Hey there, from 'console.log' inside PyScript!
in there.
Let me show another example that is slightly more involved.
setInterval
JavaScript has a function setInterval
that lets you run a function periodically.
If we write from js import setInterval
, that function becomes available to us.
That is what is being used to update the timestamp in the next paragraph.
It is now .
(If the paragraph above doesn't contain a timestamp that updates every second, something is broken! Right now, PyScript is in alpha, so that might be it... But it may be my fault as well π)
What code did I use to get that to run? Not much! In this blog post, I just had to link to the PyScript JavaScript file, and then I added the following HTML/Python code:
<py-script>
import datetime
from js import setInterval
from pyodide import to_js
def update_timestamp(elem):
elem.write(
format(datetime.datetime.now(), "%H:%M:%S, %A, %d %B %Y")
)
elem = Element("timestamp_updater")
_ = setInterval(
to_js(lambda: update_timestamp(elem)),
1000 # Update every 1000 ms
)
</py-script>
Pretty cool, right?
I learned this by reading a thread that was published on Twitter:
Going to be tweeting the session on @pyodide now. This is the app on top of which PyScript is built. Speakers are Hood Chatham and @RomanYurchak #PyConUS2022
β Playful Python (@playfulpython) May 1, 2022
That's it for now! Stay tuned and I'll see you around!
+35 chapters. +400 pages. Hundreds of examples. Over 30,000 readers!
My book βPydon'tsβ teaches you how to write elegant, expressive, and Pythonic code, to help you become a better developer. >>> Download it here ππ.