nesting jupyter runs
Jupyter notebooks are a great way of sharing knowledge in science, art, programming. For instance, in a recent musing, I tried to programmatically determine the color of the sky. This renders as a web page, but is also a piece of runnable code.
As such, they are also great ways to store the knowledge that was acquired at a given time and that could be reusable. This may be considered as bad programming and may have downsides as described in that slides :
Recently, thanks to an answer to a stack overflow question, I found a way to overcome this by detecting if the caall to a notebook is made from the notebook itself or from a parent.
It's as simple as this cell:
#verb = (__name__ == "__main__")
def has_parent():
"""
https://stackoverflow.com/questions/48067529/ipython-run-magic-n-switch-not-working
Return True if this notebook is being run by calling
%run in another notebook, False otherwise.
"""
try:
__file__
# __file__ has been defined, so this notebook is
# being run in a parent notebook
return True
except NameError:
# __file__ has not been defined, so this notebook is
# not being run in a parent notebook
return False
def do_verb():
return not has_parent()
verb = do_verb()
if verb : print('__name__=', __name__, '\nAm I a running this notebook directly? ', verb)
Let's see what we have in the memory:
if verb:
%whos
Let's run the above mentioned notebook by it from this URL:
if verb:
%run -n 2020-07-04-colors-of-the-sky.ipynb
verb = do_verb()
And now:
if verb:
%whos
Meaning that I can access the functions and some data from this notebook, to be used in another one.
if verb:
print('The color of the sky is equal to ', bluesky)
some book keeping for the notebook¶
if verb:
%load_ext watermark
%watermark -i -h -m -v -r -g -b