iters on ints? (reducing the need for range/xrange)

Tim Peters tim.one at home.com
Fri Nov 9 17:00:47 EST 2001


[James_Althoff at i2.com]
> ...
> What if (in post-2.2) Python the tp_iter slot in the int type was
> defined to return an xrange-like iterator such that one could do the
> following:
>
> for i in 10:
>     doSomething(i)
>
> or, more realistically,
>
> for rowIndex in table.getRowCount():
>     doSomething(rowIndex)
>
> instead of having to do the range(table.getRowCount()) thingie (or
> xrange, if one prefers)?

This isn't even half as disgusting as most people will say it is <wink>.  I
rather like it!  Write a PEP.

The usual rap against giving meaning to previously exceptional conditions is
that it harms error-detection (what if the user made a mistake, and didn't
have the new meaning in mind?  for example, introducing negative array
indices was a mixed blessing that way, often great but sometimes helping
obscure indexing bugs go undetected).

However, most times I've seen an exception due to using an int "instead of a
sequence", I do believe stuffing range() around the int was the cure:  it
wasn't so much a logic error as a spelling error.  Common newbie example:

for i in len(list):
    print list[i]

OTOH, what they really want is

for x in list:
    print x

so I'm not sure it's a Good Thing to let their first mistake "work".  It
would also be way cool that

    x = 1

sets x to 1 but

    x, = 1

sets x to 0 <wink>.

postfix-comma-considered-prefix-decrement-ly y'rs  - tim





More information about the Python-list mailing list