tags:

views:

271

answers:

4

I want to disable "return" from printing any object it is returning to python shell.

e.g A sample python script test.py looks like:

def func1():
    list = [1,2,3,4,5]
    print list
    return list

Now, If i do following:

python -i test.py
>>>func1()

This always give me two prints on python shell. I just want to print and get returned object.

+2  A: 

There's no way to configure the Python shell suppress printing the return values of function calls. However, if you assign the returned value to a variable, then it won't get printed. For example, if you say

rv = func1()

instead of

func1()

then nothing will get printed.

Eli Courtwright
+7  A: 

The reason for the print is not the return statement, but the shell itself. The shell does print any object that is a result of an operation on the command line.

Thats the reason this happens:

>>> a = 'hallo'
>>> a
'hallo'

The last statement has the value of a as result (since it is not assigned to anything else). So it is printed by the shell.

The problem is not "return" but the shell itself. But that is not a problem, since working code normaly is not executed in the interactive shell (thus, nothing is printed). Thus, no problem.

Juergen
+1: Straightening out the "shell" vs. Python confusion
S.Lott
+4  A: 

In general, printing from within a function, and then returning the value, isn't a great idea.

In fact, printing within a function is most often the wrong thing. Most often functions get called several times in a program. Sometimes you want to print the value, most often you just want to use that data for something.

Let the function just return it's value. Let the code that called the function print it out, if that is the right thing to do.

Sean Cavanagh
A: 

If you don't want it to show the value, then assign the result of the function to a variable:

H:\test>copy con test.py
def func1():
  list = [1,2,3,4,5]
  print list
  return list
^Z
        1 file(s) copied.

H:\test>python -i test.py
>>> func1()
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
>>> x = func1()  # assign result to a variable to suppress auto printout
[1, 2, 3, 4, 5]
>>>
Todd