[NEW] Provenance and Attribution: Minimize IP liability for GenAI output
Home / Blog /
How to use Brython: A guide to writing Python for the frontend
//

How to use Brython: A guide to writing Python for the frontend

//
Tabnine Team /
5 minutes /
June 2, 2021

Python for frontend seems a bit counter-intuitive for anyone who has ever developed the frontend of applications. Traditionally, Python is considered a backend language. Anything web and frontend is predominantly HTML, CSS, and JavaScript.

When we say Python, we do not always think of frontend web. More like never. However, Python can be used for either front-end or back-end development. That said, JavaScript is the default language of the web.

Frontend web development deals with building web interfaces that a user can use and interact with. Everything we see in the browser is run through a coordination of HTML, CSS, and JavaScript. So how can Python be used for the front end?

Well, there’s a big little Python library called Brython that makes it all possible.

Brython stands for ‘Browser Python’ and is Python’s implementation of JavaScript. In a way, Brython is a Python-to-JavaScript compiler. It lets you write client-side code in native Python and compiles it out to HTML, CSS, and JavaScript for you.

To work with Brython, you don’t need to know JavaScript. However, you still need a proficient understanding of HTML, CSS, and Python.

Installing Brython

There are two ways to include Brython into your Python project. The first is through pip:

 pip install brython

Then in an empty folder, run the following command:

 brython-cli --install

This will give you the following folder structure:

 brython_stdlib.js
 byrthon.js
 demo.html
 index.html
 README.txt
 unicode.txt

To run a web server locally, you can use the following command:

 python -m http.server

Or alternatively,

 python - http.server 8001

Every now and then Brython releases an update. To update your related packages, use the following commands:

 pip install brython --upgrade
 brython-cli --update

You can also add Brython to your HTML page via CDN.

 https://cdn.jsdelivr.net/npm/brython@3.8.10/brython.min.js
 https://cdn.jsdelivr.net/npm/brython@3.8.10/brython_stdlib.js

This will allow you to use Python syntax within your HTML page. If you’re familiar with Angular and React, the concept is similar when it comes to building a frontend with a library or framework. But instead of it all boiling down to JavaScript, we are dealing with Python with HTML and CSS instead.

The perks of using Brython for frontend Python instead of JavaScript is that you might already have a strong background in Python. Whilst JavaScript is easy to pick up, it does tend to have a lot of side quirks that only show up during trial and error experiences.

The other perk of using Python for your frontend is that you can unify your project under a Python umbrella, rather than spread it across multiple technologies. The more languages you have to support, the more time you’re going to need for long-term maintenance and upgrades.

Frontend Python through Brython will need you to execute Python code both in the server and the browser, give you the same access to browser APIs, manipulate the DOM, whilst letting you interact with existing JavaScript libraries — making Python for the frontend a flexible implementation.

Using Brython for Frontend Python

To use Python in your HTML page, you need to load the function brython() . Here’s an example:

 <body onload="brython()" >
    <script type="text/python">
    Your python code here
    </script>
 </body>

To link in your python script into the frontend, you can do so like this:

 http://main.py

For example, you might have a button that does something when clicked. You want the click event logic to sit inside your main.py file while the view is your HTML.

 <body onload="brython()">
  <form class="pure-form" onsubmit="return false;">
         <button
           type="submit" id="submit">Ok</button>
     </form>
 </body>

Here is an example of binding your logic to the click event in Python.

 from browser import document, prompt, html, alert
 ​
 def clickedOk(_):
      alert("Hello there!")
      return
 ​
 document["submit"].bind("click", clickedOk)

The above will run the alert() function when the button is clicked.

While Brython is Python under the hood, it is an implementation of JavaScript. You cannot have a pure Python frontend application. Why? Because the web runs on JavaScript. Nevertheless, Brython still lets you leverage your Python knowledge for rapid front-end development.

Brython works by running a JavaScript translator on Python and executing it in the browser. This is done through brython.js and brython_stdlib.js, where brython() is invoked to compile the Python code contained in the script tag within text/python type.

brython() is the main JavaScript function that exposes the JavaScript namespace. It allows for any Python code to execute and is the only JavaScript function that you need to call explicitly for Python to work properly in the frontend. __BRYTHON__ is your JavaScript global object that holds all internal objects for your Python scripts. While we don’t use this object directly, anything Python-related will be held here.

The Frontend Python Browser Module

Brython’s browser module lets you access various browser-related functionalities. It also lets you bind your values to different targets and events, allowing your frontend to be dynamically driven by data and any changes that get detected.

Here is a list of the different browser methods and what they do.

  • browser.alert(message) — this is a function that prints a message in a pop-up window and returns None.
  • browser.bind(target, event) — this function lets you event bind to a decorator
  • browser.confirm(message) — this function prints a message in a window. It will show two buttons (ok/cancel). It will return true if ok, and false if cancel is selected.
  • browser.console — the equivalent of console.log()
  • browser.document — this is an object that represents the HTML document that’s currently displayed in the browser window
  • browser.DOMEvent — Lets you access DOM events
  • browser.DOMNode — Lets you access DOM nodes
  • browser.load(script_url) — Lets you load JavaScript libraries
  • browser.prompt(message[,default]) — Lets you create a prompt via a pop up window. If your value is entered, it will return  the default empty string.
  • browser.run_script(src[, name]) — Lets you execute Python code
  • browser.window — Lets you access the browser window

Here’s an example of how you can use one of the above browser methods.

 <script type="text/python">
    import browser
    browser.alert("Hello Frontend Python!")
 </script>

Or alternatively, if you want to split out your Python code from the HTML:

 <head>
     http://main.py
 </head>

Here is main.py example:

 import browser
 browser.alert("Hello Frontend Python!")

Alternatives to Brython for Python Frontend

Brython is only one library of many others out there that are currently supporting Python in the frontend. Other major libraries include Skulpt, Transcrypt, Pyodide, and PyPy.js.

They all work as Python compilers, meaning that whatever you end up writing as your Python code is still valid. There might be a few differences, but overall, the general concepts introduced here are mostly the same.

Source: https://qastack.ru/programming/30155551/python-in-browser-how-to-choose-between-brython-pypy-js-skulpt-and-transcrypt

For example, Skulpt compiles Python code into JavaScript, in a similar fashion as Brython. However, it doesn’t have built-in functions that let you manipulate the DOM.

Transcrypt includes a command-line tool that lets you compile Python code into JavaScript, allowing for ahead-of-time (AOT) processes. The perk of Transcrypt is that it’s small. We’re talking 100KB kind of small, which makes it super fast to load. However, a compiler needs to be downloaded by the browser for it to work, making it an extra step for the user.

Pyodide is based on WebAssembly compilation and interprets Python code in the browser. There is no JavaScript compilation like the others, but it is often used with education-related spaces and libraries such as NumPy, Pandas, and Matplotlib.

PyPy.js is Python interpreter that compiles into JavaScript, making it compatible for ‘normal’ web development uses. However, PyPy.js is rather large, especially when compared to the others mentioned here. It is 10MB in size and therefore not practical for common web development uses. PyPy.js is also currently inactive with no updates or new release since 2019.

Whatever you end up using, Python for the frontend is not just a myth. While it all eventually turns into a form of JavaScript, it lets you leverage your current knowledge and skills without the need to start digging extensively into JavaScript.