简体   繁体   English

在Jupyter笔记本中使单元彼此独立

[英]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. 我想进行一些独立的计算,所有这些计算都在jupyter笔记本中的自己单元中-如果愿意,每个单元都有自己的“主要”功能。 Currently it looks like the union of all cells containing Python code is essentially one big Python program. 目前看来,包含Python代码的所有单元的并集本质上是一个大型Python程序。

In brief I am asking a Jupyter version of this question for Mathematica. 简而言之,我正在为Mathematica询问这个问题的Jupyter版本。

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. 您可以使用伪本地命名空间执行Jupyter笔记本电池jupyter_spaces魔法。

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. 假设环境中有Jupyter Spaces( pip install jupyter-spaces ),我们可以加载jupyter_spaces

%load_ext jupyter_spaces

Finally, we can execute a cell in a specific namespace, which has access to the globals variables. 最后,我们可以在特定的命名空间中执行单元,该命名空间可以访问globals变量。

%%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. 在此示例中, y在全局名称空间中将不可用,就好像我们已经在本地名称空间中执行了该单元格一样。

The documentation on PyPI or GitHub includes additional examples. PyPIGitHub上的文档包括其他示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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