Skip to content

Formatting Jupyter notebook code blocks

Rini Banerjee edited this page Aug 6, 2020 · 2 revisions

This wiki page serves to explain some conventions that will be adopted throughout the book with regards to Python code snippets.

There are two types of Python code snippet in these notebooks:

  • Python 2 code that compiles and is duplicated in one of the .py files in src-<section>
  • 'Semi-pseudocode' that does not compile.

The code from the original book is written in Python 2, whereas the Jupyter notebooks expect Python 3.

Code that compiles

If you find a function duplicated between a notebook and a Python file, follow these steps:

  1. In the terminal, run the following command on the Python file containing the function:
2to3 -w -n <your-python-file>.py

2to3 is a tool that automatically converts Python 2 files to Python 3. The -w flag makes sure the Python 3 code is written back to the same file, and the -n flag stops a backup of the Python 2 code from being generated in a separate file. After running this command, check that the file still compiles.

  1. Load the Python code into the notebook by creating a new code cell and running the following magic command:
%load -s <your-function-name>, /path/to/<your-python-file>.py

In the case of the notebooks, the Python file you are looking for will be contained somewhere within src-<section>.

This method prevents duplication of code between the Python files and the Jupyter notebooks. Devito implementations of Python functions should also be contained within the .py files and loaded into the notebooks when necessary.

Code that does not compile

For code cells that do not appear in the corresponding .py file and do not compile as code cells in the notebook, you can turn them into Markdown cells with Python syntax highlighting like this:

    ```python
    <your code here>
    ```