如何使用工作生成器表达式嵌入IPython?

时间:2009-10-28 19:16:10

标签: python embedding 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 个答案:

答案 0 :(得分:1)

列表理解很好,这有效:

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

这是生成器表达式(这是你传递给list()调用的那些)并不合适:

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

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

答案 1 :(得分:0)

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

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