Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making cells independent of each other in a Jupyter notebook

Tags:

python

jupyter

I would like to have a few independent computations, all them in their own cells in a jupyter notebook -- each cell having its own "main" function if you will. Currently it looks like the union of all cells containing Python code is essentially one big Python program.

In brief I am asking a Jupyter version of this question for Mathematica.

like image 789
smilingbuddha Avatar asked Mar 13 '16 00:03

smilingbuddha


2 Answers

You can execute a Jupyter Notebook cell in a pseudo-local namespace using jupyter_spaces magics.

For example, let's define a variable in a "normal" cell.

x = 10

Assuming Jupyter Spaces is available in the environment (pip install jupyter-spaces), we can load the jupyter_spaces magics.

%load_ext jupyter_spaces

Finally, we can execute a cell in a specific namespace, which has access to the globals variables.

%%space name_of_the_space
y = 2 * x

In this example, y won't be available in the global namespace just as if we had executed the cell in a local namespace.

The documentation on PyPI or GitHub includes additional examples.

like image 107
davide Avatar answered Nov 19 '22 04:11

davide


Variables defined in cells become variables in the global namespace. To isolate variables to a local scope, put them in functions:

In [1]: 

    def foo():
        x = 1
        return x
    foo()

In [2]: 

    def bar():
        x = 2
        return x
    bar()
like image 29
unutbu Avatar answered Nov 19 '22 05:11

unutbu