Random Numbers

Learn how to use Transcrypt to call JavaScript functions from Python and vice versa.

We'll cover the following...

JS functions

At its most basic, Transcrypt allows Python code to call JavaScript functions and enables JavaScript functions to call Python functions. Let’s look at an example that explicitly does both.

This simple example is similar to the previous “Hello, World!” application we did:

def get_number():
new_val = int(window.Math.random() * 10)
document.getElementById('myval').innerHTML = new_val
<!DOCTYPE html>
<html lang="en">
<body>
<script type="module">
import * as getnum from './__target__/js_function.js';
window.getnum = getnum;
</script>
<button type="button" onclick="getnum.get_number()">Click Me!</button>
<div id="myval">?</div>
</body>
</html>

Running the application

Use the following command to generate a JavaScript file from our Python code. But this time, let’s transpile the Python code with a few options:

transcrypt --nomin --map js_function

The options in the Transcrypt command did a few things for us. First, the --nomin option causes the resulting JavaScript file not to be minified. This makes it a little easier to see how Transcrypt converts our Python ...