Modules adapted to Basthon
With Basthon, some modules are used a little differently than with the usual interpreter (see also the differences with Python on a computer). These differences are described here. Every available module is listed on the Available Python modules page.
Matplotlib/Pyplot
Figures are shown in the graphical output of the console or below the cell of the notebook. They are interactive: coordinates under the mouse, zoom, pan and download of the figure (PNG, SVG, PDF…) with the toolbar below the figure.
As on a computer, plotting draws in the current figure. With the usual interpreter, closing the window opened by plt.show() also closes the figure, and the next plot starts a new figure. In Basthon, the displayed figure is never closed: it stays the current figure, and a new plot, even in a later run, is added to it. To force Matplotlib to use a new figure, call plt.figure() at the start of the script (or before each new plot).
To animate a figure, plt.pause(t) updates it then waits t seconds: in a loop, the figure is built step by step while the program runs, and it is shown only once (example). During the loop, the toolbar does not respond: the figure becomes interactive again at the end of the program. The animations of matplotlib.animation (FuncAnimation) are also shown.
Turtle
To use Turtle in Basthon, the drawing must end with turtle.done() (or turtle.mainloop(), turtle.exitonclick()), otherwise nothing is shown.
The animation can also be turned off at the start of the drawing with turtle.animation("off") (or turtle.tracer(0)) to get the final result straight away (turn it back on with turtle.animation("on")).
The drawing is computed entirely before being shown: events (onkey, onclick, ontimer…) are therefore not available. On the other hand, textinput and numinput ask their question like input.
The result can be downloaded with turtle.download("my_drawing.svg"), but beware: few applications support animated SVGs. Turn the animation off to get a more portable file.
The SVG is available with turtle.svg() and can be saved (in the virtual filesystem) with turtle.save("my_drawing.svg").
tkinter
tkinter programs work unchanged: windows, buttons, entry fields, canvases, menus, ttk widgets, dialogs (messagebox, simpledialog…). Each window (Tk()) is shown in the graphical output of the console or below the cell of the notebook, and reacts to the mouse and the keyboard.
import tkinter as tk
window = tk.Tk()
value = tk.IntVar(window, 0)
tk.Label(window, textvariable=value, font=("Arial", 32)).pack(padx=40, pady=10)
tk.Button(window, text="+ 1", command=lambda: value.set(value.get() + 1)).pack()
window.mainloop()A few differences with a computer:
mainloop()returns at once: the window stays active while the rest of the program or other cells run, which can read what was typed. Dialogs, however, do wait for the user's answer;- to use the keyboard in a window, click in it first;
- to animate, use
after(rather than a loop withsleep): the window stays responsive; - the look is that of Tk on Linux, whatever the system, and Tcl scripts (
root.tk.eval(...)) are not available.
Pillow images are shown as on a computer, with ImageTk.PhotoImage (from an image or a file); its paste method replaces the image shown, for instance after a filter:
import tkinter as tk
from PIL import Image, ImageFilter, ImageTk
window = tk.Tk()
image = Image.radial_gradient("L").convert("RGB")
photo = ImageTk.PhotoImage(image)
tk.Label(window, image=photo).pack()
tk.Button(window, text="Edges",
command=lambda: photo.paste(image.filter(ImageFilter.FIND_EDGES))).pack()
window.mainloop()tkinter is not available with the legacy kernel. Examples (a counter, a drawing program, a brick breaker) are in the gallery.
p5.js
Attention
The p5 module of Basthon is not the module you get with a pip install p5. It is a special port of p5.js for Basthon, which uses p5.js 1.11. The list of the available function names is here: https://p5js.org/reference.
A sketch is made of the setup (called once at the start) and draw (called at each frame) functions, and is started with run(). The event functions (mousePressed, keyPressed…) are found automatically when they have their p5.js name. stop() stops the sketch.
from p5 import *
def setup():
createCanvas(200, 200)
def draw():
background(220)
circle(mouseX, mouseY, 30)
run()To use p5.js, it is handy to write from p5 import *. Unfortunately, some functions of p5.js have the same name as functions of the language. This is the case for abs, float, hex, int, max, min, pow, print, round and str: Python's functions are then kept. On the other hand, filter, map and set are very different from their namesakes: Basthon then looks at the number and the type of the arguments to know whether the user wants Python's functions or those of p5.js.
Some functions of p5.js change internal variables. For instance, createCanvas changes width and height. In Basthon, these variables are only updated when the setup and draw functions are called. Their update can be forced with update_variables().
To show several independent sketches (in a notebook for instance), the instance mode, from p5.instance import *, passes the sketch as a parameter of setup and draw (sketch.createCanvas(200, 200)…), and run(setup, draw) returns a sketch that stop(sketch) stops. An example is in the gallery.
The classes of p5.sound (SoundFile, Oscillator, FFT…) are imported by from p5 import * too.
Info
For the sketch to react to the keyboard, click on it first. The webcam (createCapture) asks for a confirmation at each call. Sound (p5.sound: loadSound, Oscillator, FFT…) works. A few features (playing videos and audio files with createVideo and createAudio, capturing the microphone, loading libraries with load_library) are only available with the legacy kernel: see the documentation on isolated kernels.
Graphviz
When the render function is called on a graph, Basthon offers to save the file, as if you had just downloaded it.
Astuce
When calling render on a graph in PNG format, use the scale argument to increase the resolution.
PythonTutor
To use PythonTutor, call the tutor function of the tutor module, like this for instance:
from tutor import tutor # or 'from tutor import *' or simply
# 'import tutor' and call tutor.tutor()
# put here the code to visualize
a = 5
a = a + 1
tutor() # can also be put before the code to visualize
# the options of PythonTutor can be given as parametersAttention
The code that runs (the script in the console, the cell in the notebook) must hold all the information PythonTutor needs: declarations of variables, of functions, etc. The import of tutor itself can however be done before.
Info
When the code to visualize uses the input function, the call to tutor() must be put at the end of the script, since all the user's inputs must have been recorded to make the animation. Moreover, if you use input outside of PythonTutor, the inputs may need to be cleared with tutor.clear_inputs() at the start of the script:
from tutor import tutor, clear_inputs
clear_inputs()
name = input("What is your name? ")
print("Hello", name)
tutor()QRCode
A few features were added to the qrcode module. For instance, the image of a code can be downloaded without saving it.
import qrcode
my_code = qrcode.make("A great message!")
my_code.download()The format (png, the default, or svg) is easily chosen with the format parameter of the make function.
import qrcode
my_svg_code = qrcode.make("A great message!", format='svg')
my_svg_code.show()RCViz
The API of rcviz was redesigned to be handier and more flexible. In Basthon, this module is used like this:
from rcviz import viz
@viz
def total(n):
if n < 1:
return 0
return n + total(n - 1)
print(total(4))
total.callgraph() # use .render() to download the graph you get, or
# basthon.display to show it (useless in the notebook)The rcviz.viz decorator thus gets the call graph from the function itself. Moreover, a new call of the function automatically makes a new graph.
Plotly
Plotly figures are shown with fig.show() (or as the last value of a cell of the notebook) and stay interactive. plotly.express needs Pandas: import it explicitly (import pandas) before using it.
Folium, Pandas, PIL and OpenCV
To show them in the console (see Displaying objects), Basthon adds a few shortcuts:
m.display()shows a Folium map;table.display()shows a PandasDataFrame;image.show()shows a PIL image;cv2.imshow(name, image)shows an OpenCV image.
SymPy
pretty_print(expression) shows an expression in mathematical form (in LaTeX) and, after init_printing(), expressions are shown this way in the notebook.
drawsvg
A drawsvg drawing is downloaded as SVG with drawing.download() (or drawing.download("my_drawing.svg")).
requests
The requests module is a simplified version (requests.get, requests.post…) that goes through the browser: the server queried must allow requests coming from another site (CORS).
ipytest
ipytest lets you write pytest tests in the console or a cell of the notebook. The %%ipytest magic command does not exist in Basthon: call ipytest.run().
import ipytest
ipytest.autoconfig()
def test_sum():
assert sum([1, 2, 3]) == 6
ipytest.run()Mocodo
Mocodo draws conceptual data models and derives the logical model or the SQL code from them. Since magic commands do not exist in Basthon, call the mocodo function of the mocodo.magic module with the text of the cell (example):
from mocodo.magic import mocodo
mocodo("""
%%mocodo
Customer: Customer ID, Name
Place, 0N Customer, 11 Order
Order: Order number, Date
""")