Running some code whenever your Jupyter notebook starts is handy and easy.
You put a some code in $(ipython locate)/profile_default/startup/00-mycode.py and improve your workflow instantly. You can avoid writing import numpy as np in every notebook, check that you’re not running a notebook with production credentials etc.
There’s a big catch, though — they fail silently. If there’s an error in running the code from startup scripts, the notebook will run as nothing has happened.
Having them fail silently is not a big deal if you’re using them to import numpy — you’ll figure it out first time you reference the variable. But if you’re using them to set up some security guardrails and they fail, you’re in trouble.
Unfortunately, there is no way to just flip some config flag and make them fail, but there is a workaround — you can write your startup script as a ipython extension. I’ll explain how to do it, and then explain the anatomy of the solution.
I’ve create a tiny repository with everything needed. There are three steps
cp -r profile_changes/* $(ipython locate)/profile_default
These steps will make sure that your code is loaded every time a kernel starts, and that it fails if your script fails.
<aside> 💡 If you change the script in the future, don’t forget to run the copy command again.
<aside> 🤖 Extensions and your python code won’t share the variable namespace. Pre-importing packages like numpy in extensions won’t work by default.
If you need that, read the post all the way to the end.
The solution consists of two components.