Sebnarvaez
Sebnarvaez

Reputation: 23

Python accessing to wrong key

I'm using a dictionary as an alternative to an if/elif structure that looks like this:

newValue = {
    'int': param.value + (random.choice((-1, 1)) * 
        random.randint(1, param.maxChange)),
    'float': param.value + random.uniform(-param.maxChange,
            param.maxChange),
    'bool': not param.value
}[param.dataType]

but when param.dataType is 'float', it access to the 'int' value. If I use the if/elif structure, it works as expected.

if param.dataType == 'int':
    newValue = param.value + (random.choice((-1, 1)) * 
        random.randint(1, param.maxChange))

elif param.dataType == 'float':
    newValue = param.value + random.uniform(-param.maxChange,
        param.maxChange)

elif param.dataType == 'bool':
    newValue = not param.value

What could be wrong with the dict form? I'm using Python 2.7

Edit: It wasn't that it was accessing to the wrong key. I was getting an exception belonging to the 'int' block of code, so I thought it was trying to assign the value from 'int' to newValue.

Upvotes: 1

Views: 630

Answers (1)

Peter
Peter

Reputation: 553

In your code the dictionary is first instantiated and the 'int', 'float', and 'bool' entries are added. As part of adding the entries, the expressions for int, param.value + (random.choice((-1, 1)) * random.randint(1, param.maxChange)) as well as the other expressions are evaluated. This will lead to problems if the parameter does not have the correct data type. To fix it you could try the following: (untested because you did not provide a working example)

newValue = {
    'int': lambda param: param.value + (random.choice((-1, 1)) * 
        random.randint(1, param.maxChange)),
    'float': lambda param: param.value + random.uniform(-param.maxChange,
            param.maxChange),
    'bool': lambda param: not param.value
}[param.dataType](param)

Now the entries are holding lambda functions and the code should only be evaluated once called.

In addition, the dictionary has be created every time this code runs. If this part of the code runs multiple times, it should be more efficient to create the dictionary once and then use it multiple times.

Upvotes: 1

Related Questions