如何将 IPython 嵌入到工作生成器表达式中?
当我按照说明嵌入 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
列表推导式很好,这有效:
它是生成器表达式(这是您传递给
list()
调用的内容),但不太好:区别:列表推导式中的项目在定义时进行评估。生成器表达式中的项目在调用
next()
时进行计算(例如,当您将其传递给list()
时通过迭代),因此它必须保留对范围的引用它是在哪里定义的。该范围引用似乎处理不正确;这很可能只是一个 IPython bug。List comprehensions are fine, this works:
It's generator expressions (which is what you passed to that
list()
call) that are not fine: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 tolist()
), 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.似乎可以工作,但 IPython 认为它是主程序。因此,在实例化 IPShell 后,崩溃会显示“哎呀,IPython 崩溃了”。
Seems to work, but IPython thinks it's the main program. So after instantiating IPShell, a crash shows "whoops, IPython crashed".
对于这种情况,我发现以下更新了范围,以便可以找到
bar()
:For this situation, I've found the following updates the scope so that
bar()
can be found: