如何将 IPython 嵌入到工作生成器表达式中?

发布于 2024-08-09 09:50:53 字数 554 浏览 9 评论 0原文

当我按照说明嵌入 IPython 0.10 时,某些列表理解无法正常工作。我的全局命名空间出了什么问题?

$ python
>>> import IPython.Shell
>>> IPython.Shell.IPShellEmbed()()
In [1]: def bar(): pass
   ...: 
In [2]: list(bar() for i in range(10))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)

/tmp/<ipython console> 

/tmp/<ipython console> in <generator expression>([outmost-iterable])

NameError: global name 'bar' is not defined

Certain list comprehensions don't work properly when I embed IPython 0.10 as per the instructions. What's going on with my global namespace?

$ python
>>> import IPython.Shell
>>> IPython.Shell.IPShellEmbed()()
In [1]: def bar(): pass
   ...: 
In [2]: list(bar() for i in range(10))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)

/tmp/<ipython console> 

/tmp/<ipython console> in <generator expression>([outmost-iterable])

NameError: global name 'bar' is not defined

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谢绝鈎搭 2024-08-16 09:50:53

列表推导式很好,这有效:

[bar() for i in range(10)]

它是生成器表达式(这是您传递给 list() 调用的内容),但不太好:

gexpr = (bar() for i in range(10))
list(gexpr)

区别:列表推导式中的项目在定义时进行评估。生成器表达式中的项目在调用 next() 时进行计算(例如,当您将其传递给 list() 时通过迭代),因此它必须保留对范围的引用它是在哪里定义的。该范围引用似乎处理不正确;这很可能只是一个 IPython bug。

List comprehensions are fine, this works:

[bar() for i in range(10)]

It's generator expressions (which is what you passed to that list() call) that are not fine:

gexpr = (bar() for i in range(10))
list(gexpr)

The difference: items in the list comprehension are evaluated at definition time. Items in the generator expression are evaluated when next() is called (e.g. through iteration when you pass it to list()), so it must keep a reference to the scope where it is defined. That scope reference seems to be incorrectly handled; most probably that's simply an IPython bug.

方圜几里 2024-08-16 09:50:53

似乎可以工作,但 IPython 认为它是主程序。因此,在实例化 IPShell 后,崩溃会显示“哎呀,IPython 崩溃了”。

import IPython.Shell
ipshell = IPython.Shell.IPShell(argv=[], user_ns={'root':root})
ipshell.mainloop()

Seems to work, but IPython thinks it's the main program. So after instantiating IPShell, a crash shows "whoops, IPython crashed".

import IPython.Shell
ipshell = IPython.Shell.IPShell(argv=[], user_ns={'root':root})
ipshell.mainloop()
千里故人稀 2024-08-16 09:50:53

对于这种情况,我发现以下更新了范围,以便可以找到 bar()

globals().update(locals())

For this situation, I've found the following updates the scope so that bar() can be found:

globals().update(locals())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文