Why does typing a variable (or expression) print the value to stdout?

亡梦爱人 提交于 2019-11-28 07:01:24

问题


Take this example:

>>> 5+10
15
>>> a = 5 + 10
>>> a
15

How and why does Python do this without an explicit print statement?

If I do the same thing in an IPython cell, only the last such value is actually printed on stdout in this way:

In[1]: 5+10
       1

Out[1]: 1

Why does this happen?


回答1:


When Python is in "interactive" mode, it enables certain behaviors it doesn't have in non-interactive mode. For example, sys.displayhook, originally specified in PEP 217.

If value is not None, this function prints it to sys.stdout, and saves it in __builtin__._.

sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session.

You can modify this behavior:

>>> import sys
>>> def shook(expr):
...   print(f'can haz {expr}?')
...
>>> sys.displayhook = shook
>>> 123
can haz 123?
>>> False
can haz False?
>>> None
can haz None?

And also set it back to normal:

>>> sys.displayhook = sys.__displayhook__
>>> 3
3

In the default Python repl, sys.displayhook is

>>> import sys;
>>> sys.displayhook
<built-in function displayhook>

but in IPython it's

In [1]: import sys

In [2]: sys.displayhook
Out[2]: <IPython.terminal.prompts.RichPromptDisplayHook at 0x7f630717fa58>

So that's why you see different behavior between Python and IPython.




回答2:


That's how all interpreters work. They don't need any print, but one thing, and without print they do the repr of everything, and print doesn't, example:

>>> 'blah'
'blah'
>>> print('blah')
blah
>>> 

Look at the quotes.

Also see this:

>>> print(repr('blah'))
'blah'
>>> 

repr does the same.



来源:https://stackoverflow.com/questions/54859437/why-does-typing-a-variable-or-expression-print-the-value-to-stdout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!