Wednesday 10 October 2012

When True Was True When It Should Have Been False

(or Why The Devil Is In The Details)

Another 'whoops' moment in class today - another little lesson learned by the teacher: always read the documentation carefully.

In this case, my students had been given the problem of how to 'clean up' a list in Python so that it contained only integers or floats – any strings, tuples, booleans, etc. would need to be removed.

A simple enough task - simply loop over the list and check the type of each item. But here's where the documentation (or more precisely, a cursory read of it) lead us astray.

The Python docs say this about the inbuilt type() function:
type(object)
Return the type of an object. The return value is a type object. The isinstance() built-in function is recommended for testing the type of an object.
So we should use isinstance()? Okay, let's look at that then:
isinstance(object, classinfo)
Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof.
So, we can do something like isinstance(i, (int, float)) to check the if the type of i is an integer or float.

And all seemed well right up to the point when this list:
[3, 4.5, "word", True, (3, 5)]
should have been reduced to:
[3, 4.5]
but instead became:
[3, 4.5, True]
Wha...? How did that boolean slip through?

Back to the documentation:
isinstance(object, classinfo)
Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof
When we look at the documentation on numeric data types, we find this:
There are four distinct numeric types: plain integers, long integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of plain integers.
So this:
isinstance(True, int)
returns True rather than False.

I can see some good reasons why booleans have been defined as a subtype of integers (and it's not only Python where this is the case), but it caught us offguard all the same.

So the point of today's lesson - read the documentation carefully, make sure you get your head around the finer details. Not the point I had planned to make, but maybe a better lesson as a result.

No comments: