AFAIK, Python evaluates the defaults of a function only once, at declaration time. So calling the following function printRandom
import random
def printRandom(randomNumber = random.randint(0, 10)):
print randomNumber
will print the same number each time called without arguments. Is there a way to force reevaluation of the default randomNumber at each function call without doing it manually? Below is what I mean by “manually”:
import random
def printRandom(randomNumber):
if not randomNumber:
randomNumber = random.randint(0, 10)
print randomNumber
No. The default arguments are set when they are executed, which is when the function is defined. If you wanted them to be re-executed, you would need to re-define the function.
The standard idiom, and the one you should use, is
Note the use of
None(a singleton) and theistest for object identity. You shouldn’t useif not random_numbersince there are many values which evaluate to boolean false — in particular,0.There are plenty of other ways you could do this, but there’s no reason not to follow the convention.