>>> False in [0]
True
>>> type(False) == type(0)
False
The reason I stumbled upon this:
For my unit-testing I created lists of valid and invalid example values for each of my types. (with ‘my types’ I mean, they are not 100% equal to the python types)
So I want to iterate the list of all values and expect them to pass if they are in my valid values, and on the other hand, fail if they are not.
That does not work so well now:
>>> valid_values = [-1, 0, 1, 2, 3]
>>> invalid_values = [True, False, "foo"]
>>> for value in valid_values + invalid_values:
... if value in valid_values:
... print 'valid value:', value
...
valid value: -1
valid value: 0
valid value: 1
valid value: 2
valid value: 3
valid value: True
valid value: False
Of course I disagree with the last two ‘valid’ values.
Does this mean I really have to iterate through my valid_values and compare the type?
As others have written, the “in” code does not do what you want it to do. You’ll need something else.
If you really want a type check (where the check is for exactly the same type) then you can include the type in the list:
Handling subtypes is a bit more difficult, and will depend on what you want to do.