Reputation: 116293
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
Upvotes: 1
Views: 327
Reputation: 3443
I think the best bet would be to define None
as default value for randomNumber.
def printRandom(randomNumber=None):
if randomNumber is None:
print random.randint(0, 10)
else:
print randomNumber
Upvotes: 2
Reputation: 30342
Use None
:
def printRandom(randomNumber=None):
if randomNumber is None:
randomNumber = random.randint(0, 10)
print randomNumber
Upvotes: 3
Reputation: 123662
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
import random
def print_random(random_number=None):
if random_number is None:
random_number = 4 # chosen by fair dice roll.
# guaranteed to be random.
print random_number
Note the use of None
(a singleton) and the is
test for object identity. You shouldn't use if not random_number
since 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.
Upvotes: 6