Best practice to load cell magic

I am currently writing Jupyter cell magic packages.
And now I wonder what implementation I should use to import them into the notebook.The following example is based on the package GitHub - kolibril13/jupyter-splitview: Making before/after image sliders in JupyterLab .
First of all the magic %%splity, could be registered

  • either with import jupyter_splitview
  • or with %load_ext jupyter_splitview.

Now I wonder what is the best way.
Here is a pro con list from my perception:

import jupyter_splitview
# option to reload_extension ❌
# option to unload_extension ❌
# auto-complete ✅ 
# easy to remember ✅
# Copy&Paste to normal Python won't throw an error ✅
# clear that its a Jupyter features 🟡
%load_ext jupyter_splitview
# option to reload_extension ✅ -> %reload_ext jupyter_splitview
# option to reload_extension ✅ -> %unload_ext jupyter_splitview
# auto-complete ❌ 
# easy to remember ❌
# Copy&Paste to normal Python won't throw an error ❌
# clear that its a Jupyter features ✅

And the corresponding implementations in the package are:

# for `import jupyter_splitview`
    ipy = get_ipython()

except AttributeError:
    print("Can not load SplitViewMagic because this is not a notebook")
# for `load_ext jupyter_splitview `
def load_ipython_extension(ipython):

I am looking forward to any inspiration.

In the IPython world, %load_ext extension is the usual mechanism for adding IPython extensions (%load_ext is more “IPythonic” ). It’s generally bad practice to rely on side effects from importing modules, e.g. via import extension

Like all extensions, the user needs to remember the name. It’s true that autocompletion doesn’t work here, but is autocompletion of a module name all that useful? Unlike other contexts e.g. function signatures, autocompletion is fairly useless in the context of importing a module because you should know the name of the module that you want in the first place.

Users shouldn’t blindly paste code into Python scripts. But, if you use something like nbconvert to produce a script from a notebook (e.g. via the Save and Export Notebook As feature), it is able to make magics work in pure-Python interpreters too (automatically).

So, personally, I think there’s a fairly strong case for using %load_ext :wink:

1 Like

I agree that %load_ext extension might be a cleaner solution.
But in the day-to-day context, I like it when things are easy, and I don’t have to remember extra keywords like load_ext and my IDE can auto-complete the package name for me to avoid typos. That’s why I will stay with import extension right now in my project.
Thanks for the idea with nbconvert, in real life I very rarely convert a whole Jupyter notebook into a python script, but rather recycle only certain cells in my python packages.