Making cells independent of each other in a Jupyter notebook

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.


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()

Tags:

Python

Jupyter