Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python constructor argument not random bug?

Tags:

python

random

I've just recently found this weird Python 'bug' and I wanted to see if anyone knew more about it!

for instance take the python module:

import random

class SaySomething:
    def __init__(self, value=random.randint(1, 3)):
        if value == 1: print 'one'
        elif value == 2: print 'two'
        elif value == 3: print 'three'

a = 0

while a < 10:
    SaySomething()
    a += 1

This code will for some reason print the SAME number 10 times!!! Now this I DO NOT understand. It seems that the constructor is being called with the same values 10 consecutive times. But if you print each SaySomething() you'll see that they all have different pointer addresses, so they aren't the same object.

Now if you change:

SaySomething()

to

SaySomething(random.randint(1, 3))

It runs as expected, with actual random choices being made.

Anyone know why this happens?

like image 366
Parad0x13 Avatar asked Nov 30 '22 14:11

Parad0x13


1 Answers

The problem is that the default arguments in Python are evaluated once, when the function is created. To fix this, try:

    def __init__(self, value = None):
        if value is None:
             value = random.randint(1, 3)

        if value == 1: print 'one'
        elif value == 2: print 'two'
        elif value == 3: print 'three'

This way, we shift the randomization into the function itself, instead of at the time of function definition.

like image 72
Alexander Kondratskiy Avatar answered Dec 06 '22 18:12

Alexander Kondratskiy