Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
577 views
in Technique[技术] by (71.8m points)

return - Why does returning in Interactive Python print to sys.stdout?

I ran into something different today. Consider this simple function:

def hi():
    return 'hi'

If I call it in a Python shell,

>>> hi()
'hi'
>>> print hi()
hi

It prints out the 'returned' value, even if it's just the repr. This felt odd to me, how could returning be printing to stdout? So I changed it to a script to be run:

def hi():
    return 'hi'
hi()

I ran this from terminal:

Last login: Mon Jun  1 23:21:25 on ttys000
imac:~ zinedine$ cd documents
imac:documents zinedine$ python hello.py
imac:documents zinedine$ 

Seemingly, there's no output. Then, I started thinking this is an Idle thing, so I tried this:

Last login: Tue Jun  2 13:07:19 on ttys000
imac:~ zinedine$ cd documents
imac:documents zinedine$ idle -r hello.py

And here is what shows in Idle:

Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "copyright", "credits" or "license()" for more information.
>>> 
>>> 

So returning prints only in an interactive python shell. Is this a feature? Is this supposed to happen? What are the benefits of this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all, its not returnning, and it's not related to functions. You just have an expression that evaluates to an object (big surprise! everything in Python is an object).

In this case, an interpreter can choose what to display. The interpreter you're using apparently uses __repr__. If you'd use IPython, you'd see there's a whole protocol, depending on the frontend, determining what will be displayed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...