Skip to contents

A .ipynb is a JSON document, not a text script: its source lives in the source array of each "code" cell. This concatenates those cells in document order so the result can be checked by the same text-based helpers every other language goes through (code_remove_comments(), code_library_names(), code_file_refs(), ...) — the notebook analogue of code_extract_r() purling an .Rmd/.qmd.

Usage

code_extract_py(file_path = NULL, save_path = NULL, text = NULL)

Arguments

file_path

path to a .ipynb file

save_path

if NULL, returns a text vector, else a path to save to

text

alternative to file_path, pass the notebook JSON directly

Value

a character vector of source lines (empty when the file has no code cells or is not parseable JSON)

Details

Jupyter is kernel-agnostic, so a notebook's cells may be Python or R (or another language); this extracts the source whatever the kernel, and code_lang() is what reports which language it is. The function is named for the file type it reads, not for a language it assumes.

Markdown and raw cells are dropped (they are prose, not code). Cell boundaries are preserved as blank lines so line counts stay meaningful, and IPython magics (%matplotlib inline) and shell escapes (!pip install x) are dropped: they are not statements in any kernel language and would only ever be noise to the checks downstream.

The OUTPUTS a notebook stores alongside its code are not touched here — see read_stat_tables(), which reads those as result tables the same way it reads a .jasp/.omv archive.

Examples

nb <- '{"cells": [{"cell_type": "code", "source": ["import pandas as pd"]},
  {"cell_type": "code", "source": ["df = pd.read_csv(\'data.csv\')"]},
  {"cell_type": "markdown", "source": ["# Notes"]}]}'
code_extract_py(text = nb)
#> [1] "import pandas as pd"          ""                            
#> [3] "df = pd.read_csv('data.csv')" ""