assertions to validate function parameters

Matthew Woodcraft mattheww at chiark.greenend.org.uk
Fri Jan 26 13:28:32 EST 2007


Steven D'Aprano  <steve at REMOVE.THIS.cybersource.com.au> wrote:
> The less your function does, the more constrained it is, the less
> testing you have to do -- but the less useful it is, and the more work
> you put onto the users of your function. Instead of saying something
> like

> a = MyNumericClass(1)
> b = MyNumericClass(6)
> # more code in here...
> # ...
> result = f(a, b)

> you force them to do this:

> a = MyNumericClass(1)
> b = MyNumericClass(6)
> # more code in here...
> # ...
> # type-cast a and b to keep your function happy
> result = f(int(a), int(b))
> # and type-cast the result to what I want
> result = MyNumericClass(result)


I have a question for you. Consider this function:

def f(n):
    """Return the largest natural power of 2 which does not exceed n."""
    if n < 1:
        raise ValueError
    i = 1
    while i <= n:
        j = i
        i *= 2
    return j

If I pass it an instance of MyNumericClass, it will return an int or a
long, not an instance of MyNumericClass.

In your view, is this a weakness of the implementation? Should the
author of the function make an effort to have it return a value of the
same type that it was passed?

-M-




More information about the Python-list mailing list