5

当我按照说明嵌入 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
4

2 回答 2

1

列表推导很好,这有效:

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

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

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

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

于 2009-10-29T14:19:13.777 回答
0

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

import IPython.Shell
ipshell = IPython.Shell.IPShell(argv=[], user_ns={'root':root})
ipshell.mainloop()
于 2009-10-28T19:57:51.100 回答