1

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

from random import random

def printNumber(num=random()):
    print num

for i in range(10):
    printNumber()

I want to see ten random numbers, but the ten random numbers are all the same!

Community
  • 1
  • 1
user805627
  • 4,247
  • 6
  • 32
  • 43

2 Answers2

4

Because the default arguments are only executed once, when the function is compiled.

From the Docs:

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. T

you can try something like this:

In [10]: def printNumber(num=None):
    return num if num is not None else random()
   ....: 

In [12]: printNumber()
Out[12]: 0.9620725546432438

In [13]: printNumber()
Out[13]: 0.8188258892156928

In [15]: printNumber(10)
Out[15]: 10
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Is this typical for Python or is this mechanism (default value only assigned once) more widespread? Please back up with examples. – poitroae Nov 03 '12 at 20:47
  • @Michael not sure about other languages but in python it's a normal behavior.(may be not for new programmers). See [this](http://effbot.org/zone/default-values.htm#why-does-this-happen). – Ashwini Chaudhary Nov 03 '12 at 20:50
  • @Michael I know C++ does the other thing (adds the default expression at each call site), but that has its own problems, and it doesn't make a lot of sense to compare C++ to Python here because they are so fundamentally different. Google indicates Ruby also creates a new value each time though. –  Nov 03 '12 at 20:52
  • @delnan Thank you for the info. I try to compare the mechanisms themselves, of course we can't judge about this in a few sentences. :) – poitroae Nov 03 '12 at 20:56
3

because it is executed at function inststanciation ... not on function call

the correct(er) way would be

def printNumber(num=None):
     if num == None:
         num = random()
         print num
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179