当显示没有打印功能的数据时,IPython和REPL的行为有所不同 [英] IPython and REPL behave differently when displaying data without the print function

查看:63
本文介绍了当显示没有打印功能的数据时,IPython和REPL的行为有所不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,所有实验均在Python3.4.3和IPython 5.1.0(适用于python3)上进行.

Note that all experiments have been performed on Python3.4.3 and IPython 5.1.0 (for python3).

考虑一个返回身份的函数:

Consider a function that returns the identity:

def my_func(): 
    return 1

现在,从REPL会话中的循环调用此函数.

Now, this function is called from a loop inside a REPL session.

for _ in range(3): 
    my_func()

在IPython上,什么都不显示.

On, IPython, nothing is displayed.

In [96]: for _ in range(3): 
    ...:     my_func()
    ...:     

In [97]: 

但是,在REPL上,是:

But, on the REPL, something is:

>>> for _ in range(3): 
...     my_func()
... 
1
1
1
>>>

为什么有区别?

是因为IPython所做的事情吗?我已经检查了字节码,无论哪种情况,它们都是相同的.因此,它与字节码的生成无关,而与这两种情况下的解释方式无关.

Why is there a difference?

Is it because of something IPython does? I've examined the bytecode and in either case, they're identical. So, it has nothing to do with the bytecode generation but rather with how it is interpreted in either case.

推荐答案

关于其工作方式,

For how it works, IPython compiles loops in 'exec' mode instead of 'single', so sys.displayhook is not triggered for expression statements inside a loop. The regular interactive interpreter executes anything you enter in 'single' mode. 'single' mode is the mode where expression statements trigger sys.displayhook.

对于为什么IPython这样做的原因,常规的Python行为更令人讨厌而不是有用.您很少想在循环中自动打印表达式语句的值.更常见的是,它会偶然发生,并在屏幕外滚动您感兴趣的内容.

For why IPython does this, the regular Python behavior is more annoying than useful. You rarely want to auto-print the values of expression statements in a loop; more frequently, it'll happen by accident and scroll things you're interested in off the screen.

IPython试图提供更多有用的行为.显式打印要打印的内容比显式压制不想打印的内容要直观得多.

IPython tries to provide more useful behavior. It's much more intuitive to explicitly print the things you want printed than to explicitly suppress the things you don't want printed.

这篇关于当显示没有打印功能的数据时,IPython和REPL的行为有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆