Hacker News new | past | comments | ask | show | jobs | submit login
PyScript: Run Python in your HTML (pyscript.net)
317 points by gripfx on April 30, 2022 | hide | past | favorite | 65 comments



This uses Pyodide [0] under the hood [1], which is CPython compiled to WebAssembly. In all my tests of it, loading takes a long time ~5 seconds. Coldbrew [2], another distribution of CPython on Wasm, is another option with similar load times.

And Brython [3] is a completely different option without long load time: a Python interpreter implemented in JavaScript.

If load time is important, Brython is pretty nice. If feature completeness is important, Pyodide and Coldbrew are probably best.

[0] https://github.com/pyscript/pyscript/blob/main/pyscriptjs/sr...

[1] https://github.com/pyodide/pyodide

[2] https://github.com/plasticityai/coldbrew

[3] https://github.com/brython-dev/brython


There are actually quite a few Python-in-the-browser implementations, not just those two! A couple of years ago a colleague of mine wrote up a comparison, including Brython and Pyodide:

https://anvil.works/blog/python-in-the-browser-talk

(We chose one of the Python-to-JS compilers, https://skulpt.org, for the Anvil web-app platform, because it's much lighter weight than this. It's a couple of hundred kb on the wire, and you can call to the server for any heavy lifting.)


And before all of those, 20 years ago, ActiveState had a Python ActiveX extension (in addition to Perl and TCL).


Just the word "ActiveX" brings about nightmares.


One downside with python-to-js compilers is losing easiness and speed to debug issues, which is one of the strongest points for using Python.


It also requires a server somewhere for dynamic input (i.e. Browser based notebooks).


Just 5 seconds? Sign me up. Corporate web sites take 30+ to load already.. /s


PyScript intent for using pyodide was usability with any existing library including c-extensions like numpy and other data science tools.


Transcrypt looks pretty great for my purposes, thank you!


That 5 second loading time only happends once though.


Sadly, not true. It seems like even with cache on, it still takes 5 seconds for the JIT to load everything.


Agreed, wasm loading is supposed to be cached but in practice it doesn't seem to happen.


For some reason, I can't see this linked anywhere on the site, but there is an examples page:

https://pyscript.net/examples/

(This was presented today as a pycon keynote talk!)


okay thought it wasn't working because it seems to take a long time for the spinner to go away. but I'm very impressed with the todo.py! This is what frontend should be and in 5 years or so I wouldn't be surprised to see python taking over. If only the initial payload for the python runner was smaller and if only browsers started supporting webassembly/python stack out of the box!!!

    from datetime import datetime as dt
    from utils import add_class, remove_class
    from js import console

    tasks = []

    # define the task template that will be use to render new templates to the page
    task_template = Element("task-template").select('.task', from_content=True)
    task_list = Element("list-tasks-container")
    new_task_content = Element("new-task-content")

    def add_task(*ags, **kws):
    # create task
    task_id = f"task-{len(tasks)}"
    task = {"id": task_id, "content": new_task_content.element.value, "done": False, "created_at": dt.now()}

    tasks.append(task)
    
    # add the task element to the page as new node in the list by cloning 
    taskHtml = task_template.clone(task_id, to=task_list)
    taskHtmlContent = taskHtml.select('p')
    taskHtmlContent.element.innerText = task['content']
    taskHtmlCheck = taskHtml.select('input')
    task_list.element.appendChild(taskHtml.element)
    
    def check_task(evt=None):
        task['done'] = not task['done']
        if task['done']:
        add_class(taskHtmlContent, "line-through")
        else:
        remove_class(taskHtmlContent, "line-through")

    new_task_content.clear()
    taskHtmlCheck.element.onclick = check_task

    def add_task_event(e):
    if (e.key == "Enter"):
        add_task()


> if only browsers started supporting webassembly/python stack out of the box!!

This seems highly unlikely. Each browser maker would have to have two teams now (one for JavaScript and one for Python). An additional language would add a new security/hacking vector. They would need to keep both languages at parity which would probably slow development and make testing much more complicated. Would JS and Python be able to both work on the same web page at the same time? What if both tried to interact with the same element at the same time? This is just thoughts off the top of my head. I’m sure the real issues would be much more complicated.


As a way of interacting with the DOM, this makes me very uncomfortable:

    # add the task element to the page as new node in the list by cloning 
    taskHtml = task_template.clone(task_id, to=task_list)
    taskHtmlContent = taskHtml.select('p')
    taskHtmlContent.element.innerText = task['content']
    taskHtmlCheck = taskHtml.select('input')
    task_list.element.appendChild(taskHtml.element)

We can surely make such things easier in 2022?


I imagine that if Python were supported out of the box in browsers like JavaScript is, frameworks would emerge for this sort of thing. At this point though, I'm not sure I think it's particularly likely that browsers will support additional languages instead of just preferring people compile to WASM and use some JavaScript over it.


I tried the clock example and it worked, but I needed to wait maybe 30 seconds after page load..


They don't seem to be working on Android Chrome.


Works fine for me on a Pixel 6XL. It does need to let the pyodide files load, but they get cached, so for me, having previously loaded a demo a month or so ago, it loaded the Todo app almost instantly.

A few brief delays came with the matplotlib examples but nothing too bad (seconds not minutes)


The js and css files should be hosted on a CDN otherwise people copying/pasting these demos might chew up pyscript.net resources.


Or at least add the js and css files to the zip file.

Which curiously wasnt included.


Thank you, I was searching on the front page and didn't find those example. Would be good to add this.


Based on the responses, I assume this is a silly question, but why? Why would I want to run Python in HTML?

Does Python have some libraries that JS is missing? (I could think of AI/ML libs) The examples [1] seem so slow in my browser (Firefox on an Intel-based MBP) that they are borderline unusable for me (and some of them just straight out don't load within 60 seconds, like the Bokeh, at which point I give up).

[1] https://pyscript.net/examples


If you already have a lot of domain logic in Python for your backend, that would make it easier to write a frontend living in the same codebase. (For example, imagine a framework for autogenerating forms for your Django models; this already exists server-side, but native client-side Python would give you more options. And if your framework owns both the client and server, it could autogenerate the API so you don’t even need to write one for happy-path usecases.)

If you are already using Python on the backend, not having to hire/train a completely different skill set/stack is appealing. Sure, the browser and CSS/HTML specialism is going to remain, but not having to split your team by JS vs <backend-language> would make it much easier for a team to collaborate and share work.

I think Python in the browser only has to be “almost as good” in a direct comparison for it to actually win out as the best choice organizationally for many teams.


I'd say that there's less knowledge shared between Python frontend and Python backend than between Python and JavaScript frontends. Outside of syntax and ecosystem, I wouldn't think there's much shared between Python backend and frontend.


It makes no sense to me also. One of the reasons Python so popular is due to it's interoperability with libraries written in C/C++, otherwise it's just super slow language. In the browser you can't access these fast libraries so you are left with a crap language with an even slower execution due to the interpreter VM written in JS


There are a huge number of people who would disagree with Python being a "crap" language, and the irony is that the only language supported in the browser is js. You're missing a big reason Python is popular, and it is another reason this is a big deal. The number of people that have an opportunity to make web apps opens a great deal.

Also the idea is you CAN now access those libraries like numpy, even though Python speed in general is usually overstated.


> Why?

This isn't good for most web use cases but there are some major new use cases that it enables.

Pyodide is in Python documentation all over the place, for instance on https://numpy.org/

Python has many libraries that JS is missing. Particularly the scientific computing ecosystem has a lot of very well supported Python packages but fewer JavaScript packages. They also can benefit a lot from connection to a UI.

Two key use cases for this stuff are Python education and scientific computing. Students have a hard time installing Python locally. Generally scientists want to share their results broadly, but they probably did their analysis in Python.

Here's another example of a good use case: https://www.socialfinance.org.uk/blogs/analysing-sensitive-d...


To be clear these are all use cases of Pyodide. PyScript only was released two days ago so it's harder to point to real world uses.


I think it's primarily meant as a learning tool. Here's the TL;DR from their GitHub.[1]

PyScript is a Pythonic alternative to Scratch, JSFiddle or other "easy to use" programming frameworks, making the web a friendly, hackable, place where anyone can author interesting and interactive applications.

https://github.com/pyscript/pyscript


Ah that makes sense, I didn't think of that. Thank you.


This is awesome and has so much potential!

Regarding the size of the download, I know there is ongoing work in the Pyodide project to create a much smaller python runtime that will help tremendously. Also, the script will be cached once you download it once.

EDIT: Also, you don't need NPM or anything locally to run these


Adding -Os to the Pyodide compilation flags has proven surprisingly hard: https://github.com/pyodide/pyodide/pull/1882

But some other low hanging fruit include unvendoring the special encodings for Asian languages (hopefully everyone uses utf8), the decimal library, and the xml library which are all quite large and only occasionally used.


The GitHub repo has a more concrete overview.

https://github.com/pyscript/pyscript

Would be nice if there was a demo on the page that didn’t require installing NPM and other stuff on my machine.



I really really like this, but 4 MB zipped is a bit of a hard sell :/ I've had a need to deploy small ad-hoc HTML tools at work, though, and my Python is much better than my JS, so maybe it's worth it.


Local intranet / work tools would actually be a good use case for this as the load is small (tens, hundreds, maybe thousands of employees at absolute most) and mostly the same repeat users so browser caching would make it snappy for them on future visits.

A public marketing page where it's the random internet of totally new/anonymous users who want to instantly find out info about your product would be the worst use case for this IMHO.


For one of the examples, I saw it coming down with pyscript.js - 1.1 MB, pyodide.asm data + wasm of 16 MB, and each python package as a separate wheel download (cool!), matplotlib of 6MB :)


All your megabytes are belong to us! Webassembly is the future!


Super cool.

Any reason to use a custom element `py-script` vs a script tag with custom type?


I want this so bad with every fiber of my being.


I've learned to accept my larger snake overlord. I know a lot of people work very hard on the anaconda project. It is a fork of what I consider to be actually pythonic. I am pretty sure there are a lot of big money actors working in the space to "Embrace, Extinguish, Destroy" what I know to be Python via the Anaconda project. This is really interesting stuff and is the first evidence I've seen other than money and some very specific political stuff that shows me they might do something worth something. Congrats! I will use this! I mourn what's lost, but embrace the future.


Looks pretty cool! we recently release https://play.strawberry.rocks which also uses Pyodide, can't wait to have more python stuff in the browsers!


I for one welcome our new WASM overlords


Is this similar at all to the old pyjs/pyjamas project? I had some fun playing with that but there was no way I would have ever actually made anything serious with it.


That was a very cool project, though I believe they aren't really related, even though they seem similar. Pyjs/Pyjamas was a more of a Python to JavaScript transpiler.

This is the actual CPython runtime with full standard library and many of the Python mathematical and plotting libraries compiled to WASM, running in the browser. It can also be included with other HTML and JavaScript on a web page just by wrapping the Python in a tag.


I made a few internal UIs with it. It was easy for that and worked well (and fun). This was 2010


Thank you for posting this.

Of course it would be better if Chrome shipped with Python support, but this is a good effort. Does Wasm generally support other languages ?


wasm supports any language that compiles to wasm (or has its interpreter compiled to wasm). It's a bit like asking if "x86 assembly supports other languages"-- it supports whatever targets it!


Thank you !

This looks like a very interesting world to be apart of , I'll look at this tomorrow.

https://github.com/wasm3/wasm3


This is super exciting! Lots of potential to create easy python courses online :)


Pyodide is really cool, we got a Python library we were working on working in JS in the browser with it, including Pandas iirc, without too much trouble (though getting http requests working required a little hackery).


Python is the worst language to script anything inside a markup language that does not need to be structured like Python (HTML). So yeah, a good experiment, but unfortunately it is doomed to fail.


You can just reference your separate python file, you don't actually have to put it all in one html file.


Is there a playground/fiddle?


Why not <py></py> instead of <py-script></py-script> ?


The project uses custom elements, which are required to contain a dash.


Correct, this is referenced in one of the HTML myths I bust here: https://alanhogan.com/html-myths


cool project, check out https://gradio.app/ as well, makes a web demo with just python


I suppose this is how I can get python into flutter app too?


Now there's an Idea!


Don't hate me for saying this, but I can imagine combining this with Electron and develop desktop apps with Python.


Isn’t the whole point of electron that people don’t want to learn a new language?

Asking these web devs turned desktop app developers to learn python is probably a bridge too far…


No, the point is companies/devs want to one codebase to work on all 4 platforms. (Win, mac, linux, browser)




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: