Thursday, December 13, 2012

Brython: Browser Python

100th post

Wow, already the 100th article on the Raspberry Pi Python Adventure blog. I didn't think I'd get there that quick when I started it back in august. Still, if I could type 10x faster, I'd be talking about my 1000th post... It's a race you can never win, and that's too bad.

Fibonacci again

If you've been following the blog for at least a month, you've seen various mentions of Fibonacci numbers. It is a sort of mathematical Hello World for me. I can demo all kinds of Python related things (modules, techniques etc) with them.

Brows-onacci

I've shown how to print the Fibonacci numbers, to have the Pi speak them and to draw them (even into something that looked like flowers). But you've not seen me do the following before, python in your browser :



So, what do we have here? A textbox with some code, and if you are reading this on my website, you should be seeing the result in a yellow box, below the grey box.

If you are getting this through email or RSS, you probably wont see the result (and it is not yet on my mobile version of the site, either). I see you are a bit puzzled by what is going on... Is this for real? I see you reaching for the view page source already, but stick with me for a little while longer.

The code

Everything in the main section looks like the first Fibonacci script I had posted, that is, with the exception that print() has been replaced with webprint(). And what is webprint()? It is a function I define, and it has only 1 line:

doc['result'] <= str(x) + BR()

If you are thinking, that is just unusual for Python, then you are right. How can a boolean value print, and what is BR()?

We are looking at Python code, but with certain adaptations, due to how web browsers works:

An HTML page is seen as a tree whose root node is represented by the tag doc. And doc['result] is a node with an id named result (in our case, a <td></td> section for the results).

Subsequent nodes are either built-in Python objects or objects created by the functions corresponding to their HTML tag. In this case BR() corresponds to <BR />.

And the <= is not a lesser or equal comparison, it is a special assignment to add a child node.

I am thus sending a string representation to the browser's document item with an id of 'result', and creating a linefeed with <br />

This browser specific implementation of Python is called Brython.

Brython

Back in November, I posted a blog article about Brython (Utopie Python ou realite), but quite a few readers probably missed the significance of this, the reason being that the article was in French.

I didn't post it in English, because Pierre Quentel, the creator of Brython, wanted to first get some feedback from a smaller community before a more widespread distribution.

I saw the potential right away, and started experimenting with it. As I found issues, I sent them to Pierre, and he corrected them. I'm not sure if he sleeps at all...

The other thing that prevented a widespread release was the lack of documentation in English.  So I gave Pierre a hand, and the documentation is now fully translated. I got to learn a lot about the internals of Brython in the process.

So, what is it?

Like I said, Brython is a browser specific implementation of Python (Python 3 syntax). At this time, the main features it lacks are list comprehensions, the ternary operator and classes.

Quoting the author:
"HTML5 brings a new potential to web applications on all platforms : PCs, smartphones, tablets, TV etc
At the moment, only Javascript is supported for local client programming. The objective of Brython is to be able to use Python instead of Javascript"

It supports Ajax, HTML5 canvas, local storage, embedded audio and video. It also has alert(), confirm() and prompt(), which should be familiar to those using Javascript. And there is ton more stuff.

How does it work?

How can this work, how can we put Python code in a web page and it runs? That is because Brython takes the Python code and converts it on the fly to Javascript code, and then runs that. Everything runs in your web browser. There is nothing running on my server.

You can see the code it generates by accessing the online console on the official site.

How do I use it?

That is really the beauty of Brython, how to use it. It is not an online console or tutor helper, it is a mechanism to use:

<script type="text/python">
python code goes here
</script>

instead of type="text/javascript".

For this to work (until that is the day where browsers support this natively), we have to include brython itself: brython.js

And then run it when the page loads, through the <body> tag like this:


<body onLoad='brython()'>

Show me more!

On the brython site, you'll find quite a few interesting demos in the gallery, including these HTML5 canvas and local storage demos:

analog clock
drag and drop
local storage

I'll be starting to post some code in interactive mode, using Brython, so keep an eye on the blog!

Conclusion

Brython is brand new, but already it is quite usable. I think it will take off and become a fairly important project in the long term. No doubt, you'll want to keep an eye on it.

The website for Brython is www.brython.info

The English documentation: www.brython.info/doc/en/index.html

The google code page: code.google.com/p/brython/

The english google group: groups.google.com/forum/?fromgroups=#!forum/brython

Questions? Just leave a comment!

François

5 comments:

stuaxo said...

Hi,
This has great potential. I believe there are a bunch of unit tests that Pypy + other compatible pythons use to test their implementation.

I guess skuplt may have some useful tests too.

Cheers

Alice said...

Bonjour,

Connaissez-vous pyjs.org ? Pourriez-vous clarifier les avantages que vous voyez à brython par rapport à pyjs ?

Merci d'avance.

Nicolas38 said...

pyjs est un toolkit fait pour créer des applications complètes écrites entièrement en python. Le code python de l'application est compilé par le développeur sur la machine de développement. Le code généré est du javascript ; donc exécutable dans un browser. L'interface utilisateur utilise les widgets du toolkit pyjs.

Brython remplace javascript dans un code HTML. L'interface utilisateur reste écrite en HTML. Le code python est compilé à la volée et exécuté sur la machine cible (le browser). HTML5 est un mix de HTMK/javascript/CSS. On pourrait dire que grâce à Brython, on a maintenant HTML5+ : HTML/Python/CSS.

Francois Dion said...

Brython fonctionne sans serveur. Tout ce qu'il faut, c'est le fichier brython.js, et une page html du genre:

<!DOCTYPE html>
<html>
<head><script src="brython.js"></script></head>
<body onLoad="brython()">
<script type="text/python">
for i in range(2):
alert(i)
</script>
</body>
</html>

De sorte que l'on développe notre code de la même façon que si on le faisait en javascript, en mode immédiat avec notre navigateur web. Les erreurs Python se voient directement sur la console JS.

Brython fonctionne également avec tout les modes de déploiement (cgi, fastcgi, wsgi etc) et tout les frameworks.

Francois Dion said...

Just a follow up, I had said:
"At this time, the main features it lacks are list comprehensions, the ternary operator and classes."

This is no longer true. Brython now has all these things. And as for the little things that are missing (a method here and there), it is improving daily.