Python scripts from notebooks

Extract Python scripts from notebooks with nbdev
fastai
nbdev
jupyter
Published

April 25, 2023

Abstract

I use nbdev to write python libraries (I will create a blog entry explaining that).

And used it to blog (now only using quarto)

Sometimes you need something lighter just to export part of notebooks and reused it elsewhere (in another notebook for example).

In the old time of fastai, I used a script from Jeremy Howard (see Generate python modules from jupyter notebooks)

I want to update this method and use nbdev.

Pre-requisite

Have nbdev installed in your environment, and update it if needed

installation

conda activate <my_env>
conda install -c fastai nbdev

update

Just re-run conda install -c fastai nbdev

display version

import nbdev

nbdev.__version__
'2.3.12'

Usage

create python script

Start from a notebook, and

  • add #|default_exp app in a cell of your notebook, where app is the name of the module to be extracted
  • add #| export in each cell you want to extract
  • insert this in the last cell of your notebook. ‘path’ will be the module location
import nbdev
nbdev.export.nb_export('app.ipynb', 'path')

Execute the notebook, it will create an app.py file in path

use this python script

One can use this in another notebook:

  • from the same directory just by importing this script: import app

  • from a different directory by setting syspath:

import os, sys
from pathlib import Path
home = str(Path.home())
sys.path.append(os.path.abspath(os.path.join(home, 'path')))

and then import app

Example

create python script

#|default_exp example_nbdev
#|export

def nbdev_print():
    print('This is a nbdev example')
from nbdev.export import nb_export
nb_export('2023-04-24-extract-python-scripts-with-nbdev.ipynb', '.')
!ls -l *.py
-rwxrwxrwx 1 guillaume guillaume 251 Apr 25 10:43 example_nbdev.py

use this python script

import example_nbdev

example_nbdev.nbdev_print()
This is a nbdev example