>>> 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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With