why not say just what wants an integer?

Steven Taschuk staschuk at telusplanet.net
Fri Apr 25 11:06:12 EDT 2003


Quoth Adam Hupp:
> On Wed, Apr 23, 2003 at 10:27:08AM +0800, Dan Jacobson wrote:
  [...]
> > TypeError: an integer is required
  [...]
> > BTW, couldn't python be improved by saying just what wants an
>   integer?
> 
> It's generally bad form to smash everything on one line like that.  A
> message like "range requires an integer" would be somewhat more useful
> though.

Though only somewhat.  It's easy to imagine cases in which the
non-integer had been passed down a few layers of call and only
detected as invalid in a function which the user didn't think
they'd called.  For a simple case:

    import random

    def choose(n, k):
        """Choose k random values from [0,n), in some random order."""
        unselected = range(n)
        selected = []
        for _ in range(k):
            val = random.choice(unselected)
            selected.append(val)
            unselected.remove(val)
        return selected

Then the exception raised by choose(3, 'foo') would not be more
perspicuous for mentioning range.

It *would* be more perspicuous if it mentioned the value which is
not an integer but should be, say by
    raise TypeError('%r is not an integer' % val)
Even better would be for tracebacks to include argument values, as
was suggested lately.

-- 
Steven Taschuk                staschuk at telusplanet.net
"I tried to be pleasant and accommodating, but my head
 began to hurt from his banality."   -- _Seven_ (1996)





More information about the Python-list mailing list