Python

bool is instance of int in Python


4th of December 2008

I lost about half an hour just moments ago debugging this and pulling out a fair amount of hair. I had some code that looked like this:

 result = []
 for key, value in data.items():
    if isinstance(value, int):
        result.append(dict(name=key, value=value, type='int'))
    elif isinstance(value, float):
        result.append(dict(name=key, value=value, type='float'))
    elif isinstance(value, bool):
        result.append(dict(name=key, type='bool',
                           value=value and 'true' or 'false'))
 ...

It looked so simple but further up the tree I never got any entries with type="bool" even though I knew there were boolean values in the dictionary.

The pitfall I fell into was this:

 >>> isinstance(True, bool)
 True
 >>> isinstance(False, bool)
 True
 >>> isinstance(True, int)
 True
 >>> isinstance(False, int)
 True

Not entirely obvious if you ask me. The solution in my case was just to change the order of the if and the elif so that bool is tested first.



Comment

Show all 8 comments
 

Commenting is currently disabled in Mobile version