Much to the satisfaction of our readership, our work continues to update the Python books . But the search continues in this direction - and today we would like to mention Brython - Python for browsers. The article is short, a little playful and detective, we tried to keep the author's style.
This article provides a quick introduction to working with Brython , a Python implementation for front-end (browser) development.
The entire project is posted here .
Introduction
Envious of the success of JavaScript programmers, python conspirators met in secret to discuss the future of Python in this apocalyptic world. JavaScript is everywhere, eating up Python's clearing. Armed with Node.js , JavaScript has invaded Python territory, and it has lost its dominant role as the beloved server-side language where it previously rivaled Ruby ( remember those days ?). Then it's time to take a foray into the heart of JavaScript territory: the browser.
Don't forget your story (and remember the future)
This dilemma was not confined to the aforementioned conspirators. There was another cloak and dagger knight, the author of Transcrypt . He decided to write a compiler for Python that compiles code straight into JavaScript. As a good poisoner, he left no trace of Python behind him. It looked promising.
Others preferred to take advantage of the history lessons. Just immigrate with the whole family. At least that's how the creators of Pyodide thought . They were going to create an enclave on the JavaScript side with a full Python interpreter that could execute Python code. Accordingly, any Python code could be run there. , including most of its data science stack, where there are bindings to the C language (e.g. Numpy, Pandas).
It also looks very promising. But initial lazy tests done by the author of Pyodide showed that the page was loading a little slow at first.
Then the conspirators did exactly in the spirit of good conspirators: they created another compiler to convert Python to JavaScript, but this time to compile to JavaScript on page load (not like Transcrypt, which compiles the code to JavaScript in advance). The Brython Brotherhood was thus formed. One snake to rule them all.
Hello world
Let's write the traditional 'Hello World'
And here's the Brython trooper (I'm talking about the compiler).
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/brython@3.8.9/brython.min.js">
</script>
<body onload="brython()">
...
</body>
In the tag
body
shown above, we write the code in Brython:
<script type="text/python">
from browser import document
document <= "Hello World"
</script>
We just add Hello World to the element
document
. Hmm. Very easy.
In full - below.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/brython@3.8.8/brython.min.js">
</script>
</head>
<body onload="brython()">
<script type="text/python">
from browser import document
document <= "Hello World"
</script>
</body>
</html>
In this case, the page will simply display the greeting โHello Worldโ.
Calculator
Let's write a calculator in Brython. All his code is posted here .
Yes, you guessed it, we need a table. Let's do it.
from browser import document, html
calc = html.TABLE()
Let's add only the first row. That is, we will display the field for numbers (let's call it
result
) and the C key.
calc <= html.TR(html.TH(html.DIV("0", id="result"), colspan=3) +
html.TD("C"))
Yes, I'm not too sure about this syntax with
<=
. But, judge for yourself, such a cool library, so I agree to it.
Now let's add the keyboard
lines = ["789/", "456*", "123-", "0.=+"]
calc <= (html.TR(html.TD(x) for x in line) for line in lines)
Finally, add
calc
to
document
.
document <= calc
So, so far so good. How do we get all this to work? First, you need to grab a reference to the result element to manipulate it when the keys are pressed.
result = document["result"] # id
Next, we need to update
result
every time any element on the keyboard is pressed. For this, let's make an event handler. Let's put our trust in the Brython developers and find this code works. Pay attention to manipulations
result
depending on which button you pressed.
def action(event):
""" "click" ."""
# , , "target"
# event
element = event.target
# , , "text"
value = element.text
if value not in "=C":
#
if result.text in ["0", "error"]:
result.text = value
else:
result.text = result.text + value
elif value == "C":
#
result.text = "0"
elif value == "=":
#
try:
result.text = eval(result.text)
except:
result.text = "error"
Finally, bind the above event handler to an event
click
on all buttons.
for button in document.select("td"):
button.bind("click", action)
You see how simple it was. But seriously, Brython strikes me as a masterpiece of engineering and perhaps the best illustration of my love for the Python language. Please support the developers and give them an asterisk in the Github repository !