Python AST diagrams in WordPress

I’ve updated my Python visualiser WordPress library to support generating diagrams of Python Abstract Syntax Trees (AST). It’s still at a very early stage of development and only supports a tiny subset of AST node types, but I thought people might be interested to see what was in development.

You can produce things like this:

a = 1 + 2

from an editor embedded in Gutenberg like this:

Embedding Python widgets in WordPress

I’ve got a new project that I’ve been working on lately. My thinking is that a lot of programming topics are easier to explain with small interactive tools, but standard publishing tools are targeted towards text and don’t give you a way to incorporate code. If you go your own way and publish a code-driven page you have to reinvent the wheel around lots of tooling for editing, hosting, caching, comments etc.

Since the release of Gutenberg WordPress makes it quite easy to cleanly embed custom Javascript widgets. So how about using that to teach Python?

The widget below is a working Python tokeniser. You can edit the code however you like and see the output, with a pretty accurate emulation of the official cpython tokeniser:

foo = “hello” print(foo + “world”)

This is just a first step, and it’s not very general at the moment. However, this demonstrates a lot of the required steps and should be a good basis to build from.

It’s actually broken down into two separate projects:

  • python-code-analyzer, a Javascript library that doesn’t have any WordPress dependencies. It uses React but can in principle be integrated with any other Javascript code. This does the bulk of the work.
  • wp-python-analyzer, a WordPress package that wraps the tools up into blocks that can be deployed into the Gutenberg editor.

For what it’s worth the Python execution is done using Skulpt, an existing open-source Javascript library for executing Python code. Skulpt has its problems, but it seems pretty capable for educational purposes.