No module named google.colab – why it happens & how to fix it
Code that runs in Google Colab often breaks with ModuleNotFoundError: No module named 'google.colab'
when you move it to local Jupyter, Kaggle, or a grading server. Here’s what’s going on and how to write code that
works everywhere.
1. google.colab only exists on Colab
The google.colab package is provided by Colab itself. Local Jupyter, Kaggle kernels, and many automated
grading systems don’t include it. Trying to import it there will fail unless you guard the import.
2. Make the import optional
try:
from google.colab import drive
IN_COLAB = True
except ImportError:
IN_COLAB = False
Then write Colab-specific code only when IN_COLAB is true:
if IN_COLAB:
drive.mount("/content/drive")
else:
print("Running outside Colab – skipping drive.mount")
3. Abstract Colab-only logic
If you use Colab helpers (like google.colab.files for uploading/downloading), wrap them in functions
that have fallbacks:
def download_file(path):
if IN_COLAB:
from google.colab import files
files.download(path)
else:
print(f"Download {path} from the project folder manually.")
4. Capture a portable snapshot with NoteCapsule
When your Colab notebook is finally structured to run both in Colab and locally (with guards), create a Capsule so others can reproduce the working project on their own machine.
from notebookcapsule import create_capsule
create_capsule(
name="colab-and-local-compatible",
notebook_path="notebooks/experiment.ipynb",
data_dirs=["./data"],
base_dir=".", # project root
)
The Capsule keeps all environment and path info together so you’re not tied to Colab magic.
Make Colab notebooks portable
NoteCapsule helps you turn Colab-specific projects into portable Capsules that can run on local Jupyter or other platforms, without rewiring everything right before submission.
Join NoteCapsule early access