如何使用工作生成器表达式嵌入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
解决方案 2
似乎工作,但IPython认为这是主程序。因此,在实例化IPShell之后,崩溃显示“whoops,IPython崩溃”。
import IPython.Shell
ipshell = IPython.Shell.IPShell(argv=[], user_ns={'root':root})
ipshell.mainloop()
其他提示
列表理解很好,这有效:
[bar() for i in range(10)]
这是生成器表达式(这是你传递给 list()
调用的那些)并不理想:
gexpr = (bar() for i in range(10))
list(gexpr)
区别:列表推导中的项目在定义时进行评估。调用 next()
时会计算生成器表达式中的项目(例如,当您将其传递给 list()
时通过迭代),因此它必须保留对范围的引用在哪里定义。该范围参考似乎被错误处理;最有可能的只是一个IPython错误。
不隶属于 StackOverflow