Minimal bootstrap script for running Jupyter notebooks in both local and Google Colab environments.
Solves the chicken-and-egg problem of needing setup code before you can load your setup code. This script:
- Detects whether you're running locally or in Colab
- Sets up Python paths appropriately
- Provides a simple way to upload local lib files to Colab
- Reloads lib modules during development to pick up code changes
Add this to the top of each notebook:
# === COLAB BOOTSTRAP ===
COLAB_HELPER_GIST = 'https://gist.github.com/rlogwood/720ba42326d9245390f3b162747f050c'
BOOTSTRAP_URL = f'{COLAB_HELPER_GIST}/raw/colab_bootstrap.py'
import urllib.request; exec(urllib.request.urlopen(BOOTSTRAP_URL).read().decode())
# === END BOOTSTRAP ===
# Upload lib files if in Colab (run once per session)
upload_lib() # Prompts you to select lib/*.py files (Colab only)
# Your imports
import lib.text_util as tu
import lib.wrangler as wr
# Reload modules after code changes
reload_lib_modules()Returns True if running in Google Colab, False otherwise.
Uploads local Python files to Colab via file picker dialog.
lib_dir: Destination directory (default:/content/lib)- No-op when running locally
- Creates
__init__.pyautomatically if missing - Run again anytime your lib files change
Adds the lib directory to sys.path. Called automatically when the script loads.
- In Colab: adds
/contentto path - Locally: adds
../../to path (assumes notebooks are 2 levels below the lib folder)
Reloads all currently imported lib.* modules.
- Auto-discovers which lib modules are loaded—no hardcoded list needed
- Run after uploading updated lib files or editing local lib code
- Prints each module as it's reloaded
- Run the bootstrap code
- In Colab:
upload_lib()and select your lib files - Import the modules you need
When you change lib code:
- Local: Just run
reload_lib_modules() - Colab: Run
upload_lib()to re-upload, thenreload_lib_modules()
Expected directory layout:
assignments/
├── lib/
│ ├── __init__.py
│ ├── text_util.py
│ ├── wrangler.py
│ └── ...
├── assignment1/
│ └── notebook.ipynb
└── assignment2/
└── notebook.ipynb
- Lib files are uploaded to
/content/libin Colab - The Colab filesystem resets when the runtime disconnects, so you'll need to re-upload lib files each session
- For data files that don't change often, consider using Google Drive instead
- The path setup assumes notebooks are 2 levels below the lib folder; modify
setup_paths()if your structure differs