Python: Why to assign functions’ return values to dummy variables

In response to Kototama’s comment in the previous post:

There is a need, when running directly under the interpreter (code placed in the global namespace, not inside a function or method), to assign the return value of any function to a dummy variable.

This is because when you enter an expression that has a value (other than None) in the interpreter, the value’s representation (“repr”) is printed to standard output.
Example (standard output given in blue):

>>> def add_num(mylist):
    num = max(mylist) + 1
    mylist.append(num)
    return num
 
>>> mylist = [0]
>>> mylist
[0]
>>> add_num(mylist)
1
>>> mylist
[0, 1]

That’s nice, but eventually we’ll do something like this, without giving it much thought:

>>> for i in xrange(10):
    add_num(mylist)
 
2
3
4
5
6
7
8
9
10
11

Eh?! We didn’t want those to be printed at all. Where did they come from?
“for” loop or not, the add_num calls were still directly in the global namespace and not inside a function or method, so the value of the expression was printed.

What I usually do to solve this is to put the code in a main() function and simply calling it in the global namespace.
But in the example I gave in that post, I had to specifically modify code outside main(), hence the need to assign to a dummy variable, to avoid having an expression with a value (unlike C, in Python an assignment is not an expression).

Leave a Reply