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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With