Python in the Browser: Brython

Today I’m looking at Brython.

What is it, exactly

From the website:

Brython is designed to replace Javascript as the scripting language for the Web. As such, it is a Python 3 implementation …, adapted to the HTML5 environment, that is to say with an interface to the DOM objects and events


When you use Brython, the python code is directly embedded in the HTML inside a <script type="text/python3"> tag.

Brython is currently under active development.

Licence

The Brython licence is a very permissive one similar to the MIT or BSD licences. I’m sure it’s a well-known one, but I can’t immediately identify it (being not that familiar with the ins and outs of various licences).

Installation

The brython javascript code simply needs to be loaded into the web page, and an initialisation function is executed (typically <body onload=brython(1) >). All <script type="text/python3"> tags are now interpreted correctly.

Online examples

The online examples are pretty awesome actually. The console allows you to interact with the python interpreter, and all the imports that I tried out (like import antigravity just for fun) worked. Although being a little slower on my phone, the examples I tried worked there also, except for drag and drop. I had the same problem with Skulpt, so I expect it’s the fault of the browser. The “3D walker” demo also worked on the phone, but very slowly. That’s disappointing, but not at all surprising.

A large part of the brython website is done in python (even the static text), and it’s rather slow loading because of it.

Learning Curve

The learning curve for brython is very shallow.

<script src="2015/brython/brython.js" type="text/javascript"></script>
<script type="text/javascript">brython()</script>
<script type="text/python3">
from browser import document

document[’brython_output’] <= "Hello World\n"
</script>
<pre id="brython_output"></pre>
<button type="button" onclick="brython()">Run</button>

The function call to brython() is typically made in the onload event on the <html> tag. Calling this function in a script tag doesn’t work as you can see, but calling it in a button click event handler does.

The brython documentation is very good, and using brython ‘feels’ right.

Coverage of the Python standard library

A large part of the standard library seems to be covered already – at least the common parts of it are. Brython’s goal is to provide a complete python implementation in the browser, so things are looking good in that direction.

Programming graphics

A number of the examples show graphics. There’s even some files for pygame in the brython 3.0.2 source, but importing pygame doesn’t work yet.

Conclusion

Brython is a beautiful way to do Python in the browser. It also has good documentation and a good amount of the Python library already, so it’s a very strong contender.

Posted Wednesday, February 25, 2015

Blog contents