|
| 1 | +# Live code |
| 2 | + |
| 3 | +With live coding you can make your pages more interactive by adding live, executable code cells. This extension is already part of your TeachBooks book if you started from the template. If not, you can follow instructions [in the manual](https://teachbooks.io/manual/features/live_code.html#setting-up-python-live-coding) to enable it. The template also includes a sample page with live code enabled, which you can find [here for the website of the original template](https://teachbooks.io/template/some_content/text_and_code.html) |
| 4 | + |
| 5 | +With live code enabled, readers can run snippets directly in the browser, experiment with examples, and complete exercises in real time. This section will guide you through some of the main features available: additional cell tags have been developed that can be added to Python code cells in your book. These tags extend the [existing Jupyter Book tags](https://jupyterbook.org/en/stable/content/metadata.html) and allow you to control how cells behave when live execution is enabled. |
| 6 | + |
| 7 | +::::::{topic} Exercise objective |
| 8 | +Can you apply custom cell tags to control the execution and visibility of code cells? |
| 9 | +:::::: |
| 10 | + |
| 11 | +## Available custom tags |
| 12 | + |
| 13 | +- `disable-execution-cell` disables the ability to execute the cell when live code is activated. This is useful if your notebook includes interactivity for only part of the cells. |
| 14 | +- `disable-execution-page` disables the ability to execute the entire page. This can be helpful if Python code is used to build a page but is not meant to be run by readers. |
| 15 | +- `auto-execute-page` automatically starts live coding when the page is opened, useful if you are using widgets. |
| 16 | +- `thebe-init` runs this cell automatically as soon as live coding starts. |
| 17 | +- `thebe-remove-input-init` is similar to `thebe-init` but hides the input from students while still executing it. (The regular `remove-input` tag will not work here, since it deletes the entire cell.) |
| 18 | + |
| 19 | +```{tip} |
| 20 | +Tags are case-sensitive. Use lowercase and match them exactly as shown above. |
| 21 | +```` |
| 22 | +
|
| 23 | +## Creating a notebook |
| 24 | +
|
| 25 | +There are two ways you can try this exercise, depending on whether you have an IDE installed. If you don't know what an IDE is, or don't have one installed, follow Option 2 below. |
| 26 | +
|
| 27 | +```````{tab-set} |
| 28 | +``````{tab-item} Option 1: Using JupyterLab or VS Code (if installed) |
| 29 | +
|
| 30 | +1. In your repository, create a new notebook file in your book directory, e.g. `book/live_code_tags.ipynb`. |
| 31 | +2. To add a new code cell, use `python` and enter a simple code, for example: |
| 32 | +
|
| 33 | +````md |
| 34 | +```python |
| 35 | +print("Hello world!") |
| 36 | +``` |
| 37 | +```` |
| 38 | +
|
| 39 | +With this setup, tags can be added by opening the cell metadata (in JupyterLab or Jupyter Notebook: `View → Cell Toolbar → Tags`). |
| 40 | +
|
| 41 | +`````` |
| 42 | +``````{tab-item} Option 2: Using Jupytext in Markdown |
| 43 | +
|
| 44 | +1. If you don’t have JupyterLab or VS Code installed, you can still add code in a markdown file. To make sure this is recognized as an interactive code cell, you need to add a Jupytext header. At the very top of your file (e.g. `book/live_code_tags.md`), add: |
| 45 | +
|
| 46 | +```yaml |
| 47 | +--- |
| 48 | +jupytext: |
| 49 | + text_representation: |
| 50 | + extension: .md |
| 51 | + format_name: myst |
| 52 | + format_version: 0.13 |
| 53 | + jupytext_version: 1.17.3 |
| 54 | +kernelspec: |
| 55 | + display_name: base |
| 56 | + language: python |
| 57 | + name: python3 |
| 58 | +--- |
| 59 | +``` |
| 60 | +
|
| 61 | +2. Now you can insert executable code cells like this: |
| 62 | +
|
| 63 | +````md |
| 64 | +```{code-cell} ipython3 |
| 65 | +print("Hello world!") |
| 66 | +``` |
| 67 | +```` |
| 68 | + |
| 69 | +With this setup, tags can be added directly into the code cell using `:tags:`, for example: |
| 70 | + |
| 71 | +````md |
| 72 | +```{code-cell} ipython3 |
| 73 | +:tags: ["hide-cell"] |
| 74 | +print("Hello world!") |
| 75 | +``` |
| 76 | +```` |
| 77 | + |
| 78 | +`````` |
| 79 | +``````` |
| 80 | +
|
| 81 | +## Trying the custom tags |
| 82 | +
|
| 83 | +Now that you know how to create executable code cells, let’s explore the different custom tags available and see examples of how each one can control the behavior of your code when live execution is enabled. |
| 84 | +
|
| 85 | +
|
| 86 | +### `disable-execution-cell` |
| 87 | +
|
| 88 | +3. This tag is useful when you want a particular code cell to display content without being executed by readers. For example, let’s set up a new cell that prints the current date and time only once: |
| 89 | +
|
| 90 | +```````{tab-set} |
| 91 | +``````{tab-item} Option 1: Using JupyterLab or VS Code |
| 92 | +
|
| 93 | +```python |
| 94 | +import datetime |
| 95 | +
|
| 96 | +# This prints the current date and time once |
| 97 | +current_time = datetime.datetime.now() |
| 98 | +print("This notebook was last updated at:", current_time) |
| 99 | +``` |
| 100 | +
|
| 101 | +*Remember to add the tag `disable-execution-cell` locally via the cell metadata (`View → Cell Toolbar → Tags`).* |
| 102 | +
|
| 103 | +`````` |
| 104 | +``````{tab-item} Option 2: Using Jupytext in Markdown |
| 105 | +
|
| 106 | +````md |
| 107 | +```{code-cell} ipython3 |
| 108 | +:tags: ["disable-execution-cell"] |
| 109 | +
|
| 110 | +import datetime |
| 111 | +
|
| 112 | +# This prints the current date and time once |
| 113 | +current_time = datetime.datetime.now() |
| 114 | +print("This notebook was last updated at:", current_time) |
| 115 | +``` |
| 116 | +```` |
| 117 | +
|
| 118 | +`````` |
| 119 | +``````` |
| 120 | +
|
| 121 | +4. Commit and rebuild your book and visit the page — notice that this particular cell can no longer be run when live code is activated. |
| 122 | +
|
| 123 | +### `disable-execution-page` |
| 124 | +
|
| 125 | +5. This tag is useful when you want all code cells on a page to be non-executable. This is handy if the code is used to build the page or provide context, but you don’t want readers to run it themselves. Add the tag `disable-execution-page` to any of the code cells in your file. |
| 126 | +
|
| 127 | +6. Commit and rebuild your book and visit the page — none of the cells should be executable now. |
| 128 | +
|
| 129 | +```{note} |
| 130 | +Remove this tag again before continuing, otherwise the next tags won’t have any effect. |
| 131 | +``` |
| 132 | +
|
| 133 | +### `auto-execute-page` |
| 134 | +
|
| 135 | +7. This tag is useful when you want live code to start running automatically as soon as the page is opened. This is particularly helpful when using visualizations or interactive widgets that should initialize immediately. For example, let's set up a plot: |
| 136 | +
|
| 137 | +```````{tab-set} |
| 138 | +``````{tab-item} Option 1: Using JupyterLab or VS Code |
| 139 | +
|
| 140 | +```python |
| 141 | +import matplotlib.pyplot as plt |
| 142 | +import numpy as np |
| 143 | +
|
| 144 | +x = np.linspace(0, 10, 100) |
| 145 | +y = np.sin(x) |
| 146 | +
|
| 147 | +plt.plot(x, y) |
| 148 | +plt.title("Sine wave") |
| 149 | +plt.show() |
| 150 | +``` |
| 151 | +
|
| 152 | +*Remember to add the tag `auto-execute-page` to one of the cells via the cell metadata (`View → Cell Toolbar → Tags`).* |
| 153 | +
|
| 154 | +`````` |
| 155 | +``````{tab-item} Option 2: Using Jupytext in Markdown |
| 156 | +
|
| 157 | +````md |
| 158 | +```{code-cell} ipython3 |
| 159 | +:tags: ["auto-execute-page"] |
| 160 | +
|
| 161 | +import matplotlib.pyplot as plt |
| 162 | +import numpy as np |
| 163 | +
|
| 164 | +x = np.linspace(0, 10, 100) |
| 165 | +y = np.sin(x) |
| 166 | +
|
| 167 | +plt.plot(x, y) |
| 168 | +plt.title("Sine wave") |
| 169 | +plt.show() |
| 170 | +``` |
| 171 | +```` |
| 172 | +
|
| 173 | +`````` |
| 174 | +``````` |
| 175 | + |
| 176 | +8. Commit and rebuild your book and visit the page — the plot should appear automatically without needing to click the “launch” button. |
| 177 | + |
| 178 | + |
| 179 | + |
| 180 | +### `thebe-init` |
| 181 | + |
| 182 | +9. The `thebe-init` tag is useful when you want a specific cell to run automatically as soon as live coding starts. This is especially helpful for initializing variables that other cells depend on. For example, let's initialize a dataset of student names and their scores: |
| 183 | + |
| 184 | +```````{tab-set} |
| 185 | +``````{tab-item} Option 1: Using JupyterLab or VS Code |
| 186 | +
|
| 187 | +```python |
| 188 | +# Initialize dataset |
| 189 | +students = ["Alice", "Bob", "Charlie", "Diana"] |
| 190 | +scores = [85, 92, 78, 90] |
| 191 | +
|
| 192 | +print("Initialized dataset with students and scores") |
| 193 | +``` |
| 194 | +
|
| 195 | +*Remember to add the tag `thebe-init` locally via the cell metadata (`View → Cell Toolbar → Tags`).* |
| 196 | +
|
| 197 | +`````` |
| 198 | +``````{tab-item} Option 2: Using Jupytext in Markdown |
| 199 | +
|
| 200 | +````md |
| 201 | +```{code-cell} ipython3 |
| 202 | +:tags: ["thebe-init"] |
| 203 | +
|
| 204 | +# Initialize dataset |
| 205 | +students = ["Alice", "Bob", "Charlie", "Diana"] |
| 206 | +scores = [85, 92, 78, 90] |
| 207 | +
|
| 208 | +print("Initialized dataset with students and scores") |
| 209 | +``` |
| 210 | +```` |
| 211 | +
|
| 212 | +
|
| 213 | +`````` |
| 214 | +``````` |
| 215 | + |
| 216 | +10. Commit and rebuild your book and visit the page — as soon as live code starts, this cell will run by itself. |
| 217 | + |
| 218 | +### `thebe-remove-input-init` |
| 219 | + |
| 220 | +11. This tag works similarly to `thebe-init`, but the input (code) is hidden from students, so they only see the output. This is useful when you want to initialize variables or datasets without showing implementation details. To try this, simply replace the previous tag `thebe-init` with `thebe-remove-input-init` in the same cell from the previous example. |
| 221 | + |
| 222 | +12. Commit and rebuild your book and visit the page — the cell will run automatically, but students will only see the output, not the code. |
| 223 | + |
| 224 | +13. When you are ready, commit your changes to the repository by clicking on the green `Commit changes` button. |
| 225 | + |
| 226 | +14. Add a commit message. |
| 227 | + |
| 228 | +15. To see your changes, go to {octicon}`play` `Actions` - The most recent workflow run `overview.md / the commit message of the commit you just made` - Wait for it to finish - In the summary, click on the link of your book shown in the table `Branches deployed` and under `Primary book at root` (getting bored of waiting? There'll be exercising on doing this locally which prevents you from waiting). |
| 229 | + |
| 230 | +16. Do you see your change? If you don't see it click `CTRL`+`F5`/`Control`+`F5`to refresh the page. |
| 231 | + |
| 232 | +```{admonition} Check your understanding |
| 233 | +:class: note |
| 234 | +
|
| 235 | +Before moving on, make sure you understand the following: |
| 236 | +- How do you add tags to a code cell in your book? |
| 237 | +- Which tag disables execution for a single cell? For the whole page? |
| 238 | +- Which tag makes a page auto-start live code when opened? |
| 239 | +- What is the difference between `thebe-init` and `thebe-remove-input-init`? |
| 240 | +``` |
0 commit comments