Type Hinting vs Type Checking and Preconditions

Roy Smith roy at panix.com
Tue Mar 7 19:23:13 EST 2006


In article <1141764243.936880.324240 at i39g2000cwa.googlegroups.com>,
 "Tom Bradford" <bradford653 at gmail.com> wrote:

> Here is what I mean.  The following function, though conventionally
> indicating that it will perform a multiplication, will yield standard
> Python behaviors if a string value is passed to it:
> 
> def multiplyByTwo(value):
>     return value * 2
> 
> Passing 14 to it will return 28, whereas passing "14" to it will return
> "1414".  Granted, we know and accept that this is Python's behavior
> when you multiply two values, but because we don't (and shouldn't have
> to) know the inner workings of a function, we don't know that the types
> of the values that we pass into it may adversly affect that results
> that it yields.

The question is, what is the function *supposed to do*?  Without knowing 
what it is *supposed to do*, it is impossible to say for sure whether 
returning "1414" is correct or not.  Consider two different functions:

def multiplyByTwo_v1(value):
    """Returns the argument multiplied by 2.  If the argument is a
       string representation of an integer, another string is returned
       which is the string representation of that integer multiplied
       by 2.
    """"
    return value * 2

def multiplyByTwo_v2(value):
    """Returns the argument multiplied by 2.
    """"
    return value * 2

The first one should return "28" when passed "14".  If it returns "1414", 
it's broken.  I know this seems rather silly and pedantic, but it's an 
important point.

I was once working on a project which historically didn't have any unit 
tests.  We had a function called something like "isValidIP" in the library 
which returned True or False depending on whether its (string) argument was 
a valid IP address.

I wrote some unit tests and it failed on a corner case like 
"255.255.255.255" (or maybe it was "0.0.0.0").  Turns out, the original 
author was using it in some special situation where 255.255.255.255 wasn't 
valid for his purposes.  We got down to, "OK, *you* document what the 
function is supposed to do, and *I'll* write a unit test which proves it 
does what the documentation says".  You would think that would be easy, but 
it never got done because we couldn't get everybody to agree on what the 
function was supposed to do.

It was being used in production code.  I would have thought it would bother 
people that we were using a function without knowing what it was supposed 
to do, but what really bothered people more was that we had a unit test 
that was failing.  And the solution was to back out unit test.  Sometimes 
politics trumps technology.

PS, as far as I know, that project is now dead, but for other reasons far 
worse than one underspecified function :-)



More information about the Python-list mailing list