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.

How to make startup scripts fail hard?

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

  1. Clone the ‣
  2. Copy your startup code to profile_changes/startup_extensions/extension_example.py. The load_ipython_extension function is not necessary unless you need a handle to ipython.
  3. Copy both files to the default ipython profile with following command
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>

<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.

</aside>

How does it work?

The solution consists of two components.