Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "in" does not check for type?

>>> 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?

like image 940
Martin Flucka Avatar asked Dec 19 '11 10:12

Martin Flucka


People also ask

What does type () do in Python?

Syntax of the Python type() function The type() function is used to get the type of an object. When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.

Does Python support type checking?

Luckily, Python supports the concept of gradual typing. This means that you can gradually introduce types into your code. Code without type hints will be ignored by the static type checker. Therefore, you can start adding types to critical components, and continue as long as it adds value to you.

What does check () do in Python?

Python is the most conventional way to check if an element exists in a list or not. This particular way returns True if an element exists in the list and False if the element does not exist in the list.


1 Answers

The problem is not the missing type checking, but because in Python bool is a subclass of int. Try this:

>>> False == 0
True
>>> isinstance(False, int)
True
like image 181
Constantinius Avatar answered Oct 14 '22 16:10

Constantinius