Playing with PyScript

This is something I’ve been meaning to do in javascript forever but never bothered to figure out. JS can certainly do it, but it took me about 10 seconds to do it in PyScript. The code isn’t the cleanest, but it is very straightforward.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
    <style>
    :not(:defined) {
        visibility: hidden;
    }
    </style>
</head>
<body>
    <h1>Hello! My name is <span id="name-goes-here">Kevin Goldsmith</span></h1>
    <py-script>
import random

names = ["Kevin Goldsmith", "????? ????????", "???????????", "?? ?????", "????????"]
el = Element("name-goes-here")
while True:
    name = random.choice(names)
    for n in range(0, len(name)+1):
        el.write(name[0:n])
        await asyncio.sleep(0.2)
    await asyncio.sleep(5)
    for n in range(1, len(name)+1):
        el.write(name[0:-n])
        await asyncio.sleep(0.2)
    </py-script>
</body>

A few notes:

  • I originally was going to use time.sleep(x). That didn’t work, I’m sure I can figure out why, but it was just easier to see that this method worked fine.
  • The UTF-8 encoding hints on the page are critical. I should have known this obviously, but it worked fine locally without them (of course).
  • The default PyScript unstyled my <h1>, I just got rid of it. Probably best to look at it and decide if you want those styles.
  • PyScript is fun! There are a lot of other small interactive things I want to do on my pages. As it reaches maturity, I will get them going with PyScript.
  • There is an issue sometimes where your PyScript code is visible before the code loads (I’m guessing that the default CSS fixes this). If you just want to handle that, you use the <style> code listed above.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.