简体   繁体   中英

Making cells independent of each other in a Jupyter notebook

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM