top | item 36193315

React, but in Python

238 points| filippofinke | 2 years ago |github.com

175 comments

order

crubier|2 years ago

Controversial, but I think that rather than trying to make Web stuff (e.g. React) work in Python, a more fruitful direction would be to make ML stuff (e.g. PyTorch, OpenCV) work in Typescript.

Javascript/Typescript is way faster than Python, is ubiquitous and can run pretty much everywhere, has many engine implementations, has an incredibly wide ecosystem, has a type system (Typescript) that blows any Python type system out of the water, runs in browsers, has non-stupid package management systems (PIP is a joke), is easy to get started, etc.

<The world if data scientists/ML/CV people used Typescript.JPEG>

zelphirkalt|2 years ago

The speed of the output of the compiler of the glue language almost does not matter. Whether it is Python or TypeScript, it will not matter. Typically people will not use pip directly in serious projects, except for quick and dirty package installs to prototype something. In any serious project I would expect people to use any of the package managers, that support creating a lock file. But then NPM for example is not better than poetry. Or at least I have not had a single case, where I thought: "Ah, if only it was behaving like NPM." Rather the opposite.

But anyway, the whole language specific package manager business is starting to annoy me. I would like to be able to simply use something like GNU Guix and sometimes I am able to do just that.

wraptile|2 years ago

No please no. Can we just leave javascript and all of it's flavors behind already. All of this innovation and people want to program in _transpiled_ programming language? It's like turles all the way down but it's just hacks all the way down in the js world and it'll start catching up with us if it hasn't already.

whatyesaid|2 years ago

JavaScript is a joke when you consider things like prototypes and classes. Not saying Python is perfect but JS really feels atrocious to me.

TypeScript requires you to compile, the whole point of Python for ML and data science is you're running in an interpreted environment where you delegate as much code out as you can for both data processing and algorithms to invisible C++.

The interpreted part is key as ML is about experimentation. It's not like there's any overlap between current web developers and ML people anyway to need an unified bridge.

CJefferson|2 years ago

My experience of doing maths in JavaScript was terrible. Fairly simple things like [1,2] < [10,2] return false (unlike every other language I’ve ever used), as < is implement by converting to strings, then comparing.

Is that fixed by Typescript, or does it inherit all those kinds of weird JavaScript behavior?

mountainriver|2 years ago

Good luck recreating all the data science libraries in Javascript, that was decades of work. We now have WASM so its far more likely JS just isn't needed

robertlagrant|2 years ago

Why not just implement a Typescript backend that outputs Python instead of Javascript? (-:

winrid|2 years ago

TS is a joke

tsc is the only compiler I've had to step through with a debugger multiple times.

No DS/ML researcher wants to deal with VM args just to use more than 1GB of memory. That alone would cause so much frustration.

Not to mention unpredictable generational GC.

Or the crazy crap people do with the type system (what you call better other people call a mess).

At least Python has some semblance of runtime type safety.

pwdisswordfishc|2 years ago

> has non-stupid package management systems

Excuse me what

miketery|2 years ago

Isn’t mojo the future on that front?

paulddraper|2 years ago

I'm lost.

React builds interactive UIs (web, mobile). After each interaction, the virtual DOM is programmatically recreated and reconciled to the actual DOM.

But reactpy is running on a backend sever??? Is each interaction resulting in a server call?

Can someone explain what is going on?

EDIT: Ah, okay, thanks. Every re-render is a network call. If people complained about web UI performance before..... :)

shrimpx|2 years ago

In reality, an important and large class of apps will hit the backend on roughly every click anyway, and having full control over in-browser interactivity is kind of overkill for those apps. Business apps with tables, charts, and forms, for example. You click the nav to load a new page, you scroll down or click a button to load more data, you fill a form and click submit, all those things hit the server.

For those types of apps, this 'backend-driven reactive apps' paradigm could be more efficient, because programmers don't have the option to build stuff like an inefficient network protocol or bloated frontend stack.

ledauphin|2 years ago

yes, from reading the docs, there's a websocket.

Making a 'server call' on each interaction is also what web apps used to do before SPAs were a thing. And in many cases it's what SPAs do as well.

Of course, it depends what counts as an 'interaction', but that's been the case since JavaScript existed.

quickthrower2|2 years ago

Yeah this seems to combine the worst of both worlds: react headscratching (e.g. why useEffect do this weird shit) and slowness of the phoenix style send it all back to the server. The solution? For python people: learn some JS and use django.

rch|2 years ago

Sounds like Elixir LiveView.

esprehn|2 years ago

That's how the new "react server components" work too. It's more sophisticated than this but the network concept is the same.

Blazor was the pioneer here.

narush|2 years ago

If you're interested in using React-style frontend programming in Python but want an experience / API closer to that of React, I recommend checkout out Reacton [1].

Similarly to this library, it gives you a `@component` decorator that allows you to create components out of functions. But it also: 1. Includes all existing React hooks (use_state, use_memo, etc) -- so you don't have to learn new patterns. I believe this results in a bit less magic (and so easier debugging) than just using raw variables. 2. Works with ipywidgets, so many existing data apps can be ported over very easily -- Jupyter users celebrate.

I'm not associated with the project, but I know the maintainers (creators of Volia [2]) and they are honestly excellent. I haven't use the project in production, but the getting starting guide is pretty compelling.

[1] https://github.com/widgetti/reacton [2] https://github.com/voila-dashboards/voila

bsimpson|2 years ago

I never expected to care about a UI library in Python, but my user research collaborators prefer Colab notebooks (as opposed to Observable, where my JS expertise would be relevant).

Now you (and the OP) have me pondering about building UIs in notebooks…

Not sure doing something in React is better than just learning the standard tools, but it's a good option to know exists.

ironmagma|2 years ago

I created something like this inside a tech giant once. It never saw the light of day with regard to usership. It's good to see someone doing the same in the open source world.

A brief summary of what I did:

* Python-powered apps, like this

* React was used to handle lifecycle. Basically, I avoided writing any kind of lifecycle management because I just wanted to do exactly what React would do. This was achieved via events firing when React lifecycle events fired. If props changed on the server, I'd send the new props to React to see if it would trigger a lifecycle event. If a lifecycle event was triggered, I'd replicate it onto the server which could again render new props.

* The result was a nice seamless support for both native React components and the newfangled Python components (which could be made up of either more React components or Python components).

* The purpose of all of this was to cater to ML engineers who didn't particularly like JavaScript and just wanted to build their analyses with Python and share them with coworkers. We had an automatic deployment system for them to share these.

* Only caveats were around session management. Much of the state was handled on the server via a websocket, so if your connection dropped, you lost all ability to update the layout. Load balancing was going to be tricky, since the sessions would have to be shared somehow. I was thinking about serializing and deserializing using Pickle but never really got around to deployment.

See also: [Dash](https://github.com/plotly/dash)

abhayhegde|2 years ago

Oh, I had a case where I had built an ML based recommendation app, and utilized Flask for serving the results on my localhost. Would have loved to use React but my lack of sufficient JavaScript knowledge prevented me from doing so. Your tool seemed to have perfectly catered to my needs!

devxpy|2 years ago

The way to solve session management is to just store the state in html forms and send it back to a stateless http endpoint. That way you get a website that behaves the way all websites work, and can scale easily.

ivoflipse|2 years ago

Shameless plug for a similar project called Collagraph (https://github.com/fork-tongue/collagraph).

From the README: Write your Python interfaces in a declarative manner with plain render functions, component classes or even single-file components using Vue-like syntax, but with Python!

  - Reactivity (made possible by leveraging observ)
  - Function components
  - Class components with local state and life-cycle methods/hooks
  - Single-file components with Vue-like syntax (.cgx files)
  - Custom renderers
Currently there are two renderers:

PysideRenderer: for rendering PySide6 applications PygfxRenderer: for rendering 3D graphic scenes with Pygfx

It is possible to create a custom Renderer using the Renderer interface, to render to other UI frameworks, for instance wxPython, or even the browser DOM.

TeaVMFan|2 years ago

If you're interested in this sort of thing, but want to code in Java, try Flavour: https://flavour.sourceforge.io/

Flavour is a fast, batteries-included, type-safe framework for making modern SPA web apps in Java (and other JVM languages).

* Great Lighthouse scores? Check!

* Real SPAs without sluggish network round trips? Check!

* Modern path-based routing? Check!

* Components (built-in and user-defined)? Check!

* Effortless service calls? Check!

* Refactor frontend and backend simultaneously using your current IDE? Check!

If this sounds interesting, check out these other resources:

* Article in Java Magazine: https://blogs.oracle.com/javamagazine/post/java-in-the-brows...

* 100% Flavour 5-letter word game: https://frequal.com/wordii

* Flavour podcast (created with Castini, a Flavour app): https://castini.frequal.com/cast/show/Flavourcast/f7e171e8-2...

nightpool|2 years ago

None of these links seem to work?

This site can’t be reachedCheck if there is a typo in frequal.com. DNS_PROBE_FINISHED_NXDOMAIN

garymiklos|2 years ago

Does anyone have a list of full-stack Python frameworks for building interactive web apps? I feel like a new one comes out each week, and it would be nice to see them together to compare.

shrimpx|2 years ago

There are many, but here's a start:

pyjs, streamlit, brython, pyodide, pywebio, gleam, dash, bokeh, gradio, pglet, idom, anvil, pynecone, onu

The last two are YC-funded.

Edit: add https://flet.dev which has superseded pglet

b33j0r|2 years ago

I love OP’s project. I probably won’t use it, and I say that sadly. I chased that dragon for years, but ECMA was a sleeping giant.

I do not have the answer to your question, parent, but I feel the need to evangelize vanilla JS/ECMA.

You can do everything you could do with jquery and react with very simple constructs now. Web components are slightly awkward, but damn! Possible, and easier than it ever was before js components.

Introducing any additional technologies or node is no longer necessary. The frontend has evolved.

Now. You still have to learn ECMA, but that’s what browsers definitively run as of my writing.

I can pray to mdn for wasm to be a go-to every day tech, but that day is not today.

nosnah|2 years ago

Not a list, but I've been trying out django-unicorn, which lets you build components in python and use things like unicorn:model and unicorn:click in your templates.

jraph|2 years ago

The slowest framework now available for the slowest language.

(this is a joke, it was my immediate thought when seeing this. More seriously, probably not for me but looks interesting technically, I'll need to check out how it works)

ksherlock|2 years ago

Long ago, before jsx and react, before hack, Facebook had a fork of php called xhp, which allowed xml data within php. I'm not suggesting anybody should maintain a fork of python with xml support but a pre-processor could parse xython and generate standard python with trees of html.xx() calls.

https://en.wikipedia.org/wiki/XHP

agumonkey|2 years ago

Could be fun to see this replacing jinja in old frameworks like django. Although inheritance had a better feel with templates..

rmorshea|2 years ago

ReactPy dev here. We're actually contributing to a WIP PEP that would add JS-like tagged template literals to Python. We think this will open up a whole new world of templating and DSL possibilities: https://github.com/jimbaker/tagstr

robertlagrant|2 years ago

Django doesn't use Jinja, does it? I thought it did its own thing.

quechimba|2 years ago

Nice! I believe this is a really good approach for making web apps. Best part is probably that you save time by not having to implement some sort of JSON API for your frontend to communicate with your backend.

I've been working on a similar thing in Ruby. https://github.com/mayu-live/framework

revskill|2 years ago

Nowdays, with automatic api generation for your API, there's no difference in backend/frontend communication in type-safe way.

extremeracer|2 years ago

I love this project. Having used Streamlit and Plotly Dash a lot, I find this project imposes fewer constraints. That said, it didn't support my target browser so I wrote my own and in the process (re)discovered fine grained reactive (e.g. solidjs) as an improvement over the VDOM. Anyway, the outcome was a similar approach but supporting the Kindle's browser. https://github.com/esensible/silkflow

mixeden|2 years ago

No one knows what it means, but it’s provocative

funkaster|2 years ago

from all the react clones I've seen there, this is the one that I'm mostly impressed by: https://yew.rs/ (React clone written in Rust, targeting webasm)

say_it_as_it_is|2 years ago

Hello world examples don't inspire confidence that this is anything more than a toy

TheRealPomax|2 years ago

I'm a little confused here, React might have a SSR component, but the thing that makes it React is that it runs client-side. So... how are you putting Python in the browser?

koolba|2 years ago

React doesn’t have to run client side. The DOM renderer is just one possible output, albeit the most popular. The output doesn’t even have to be human consumable.

jerpint|2 years ago

Does this offer any advantage over gradio? One big issue I have with gradio is that « simple » computations happen in the backend and make the UX very slow on deployment

jokoon|2 years ago

Please try brython, it runs in the browser.

I find it so ironic that js, a language that runs in the browser, is now used on a server, to rebuild code that is sent back to browser.

robertlagrant|2 years ago

Languages can run anywhere they have a runtime.

skratlo|2 years ago

This is cute, but it would be more helpful to have react-style GUI programming in python, with Qt (Quick or widgets) as the backend (instead of DOM).

ammar_x|2 years ago

How is this different or better than Dash or Streamlit?

est|2 years ago

might just use pyxl4, by dropbox or Guido himself.

https://github.com/pyxl4/pyxl4

example:

# coding: pyxl

from some_module import x_user_badge

user = User.get(some_user_id)

content = <div>Any arbitrary content...</div>

print <user_badge user="{user}">{content}</user_badge>

palencharizard|2 years ago

This is what's missing from the reactive-python project IMO.

A huge draw for React is that it _extends_ the JavaScript Syntax. If you still had to compose your React components with a bunch of nested `React.createElement('Component')` calls (instead of `<Component />`) it wouldn't be nearly as useful.

jcadam|2 years ago

Perhaps a Tkinter replacement, eh?

ariym|2 years ago

Don't let Dan Abramov see this

uhtred|2 years ago

I thought generating html from function calls went out with the dinosaurs. We back doing it again?

shrimpx|2 years ago

To be clear, what this comment is talking about is using `p()` and `div()` calls instead of `<p>` and `<div>` tags like in JSX.

On first read, I thought by "generating html from function calls" the author was referring the react-style way of building a UI by writing a reactive function that returns HTML.

recursive|2 years ago

I mean, react does it. It never left. JSX compiles to function calls.

uhtred|2 years ago

I feel like I'm talking to kids who have never used anything that came before react in this thread.

Stephen_0xFF|2 years ago

Still very much alive. This implementation with python, to me, doesn’t look promising, but Elixirs LiveView does.