[Python-Dev] PyRange_New() alternative?

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Fri Jun 23 12:23:19 CEST 2006

--- Tim Peters <tim.peters at gmail.com> wrote:
> [Ralf W. Grosse-Kunstleve]
> > Thanks! This does the trick for me:
> >
> > #if PY_VERSION_HEX >= 0x02030000
> >         PyObject_CallFunction(
> >           (PyObject*) &PyRange_Type, "lll", start, start+len*step, step)
> Note that this is extremely lax about possible overflow in the
> arithmetic.  For that reason it can't be recommend for general use.
> > #else
> >         PyRange_New(start, len, step, 1)
> > #endif
> >
> > I've tested this with Python 2.2.3, 2.3.4, 2.4.3, 2.5b1. Python 2.2.3
> (RedHat
> > WS 3) compiles the PyRange_Type call, but there is a runtime error:
> >
> > TypeError: cannot create 'xrange' instances
> Sorry, I didn't follow that.  The only mention of PyRange_Type in the
> #if'ed code above is in a block that looks like it should be entirely
> ignored in a 2.2.3 Python (provided you're using the right header
> files and the C compiler isn't broken).

First I tried the PyRange_Type code with Python 2.2.3 and no #ifdef. I resorted
to the #ifdef and the old PyRange_New() call only because it didn't work.

> Compile all of Python that way, and you'll probably see more of those
> than you can count ;-)  Python is normally compiled with, and is
> _intended_ to be compiled with,
>     -fno-strict-aliasing
> If you didn't do that, try it.

I missed this. Thanks for pointing it out.

> Since it was never documented to begin with, it was a "use at your own
> risk" thing anyway.  As you're currently it's only known user
> throughout all of history :-), if you do all the work of
> rehabilitating it, I'd be at best a weak -1 anyway:  one of the
> problems with PyRange_New was that its signature was wildly different
> than the builtin range()'s.  That made it a poor API for "surprise,
> surprise!" reasons alone.  That was a mistake, and I'd rather
> inconvenience you than pass that mistake on to our precious children
> ;-)

I agree, although I find it hard to believe I am that unique. I'll google for
PyRange_New in a couple of years to see how many more people got stranded. :-)

Although it will bias the measure of my uniqueness, I still believe you should
tell people in the documentation what to do, e.g.

  PyObject_CallFunction((PyObject*) &PyRange_Type, "lll", start, stop, step)

which avoids showing the sloppy start+len*step hack.

BTW: by the time my children pick up programming nobody under 30 will use C
Python anymore. ;-)

Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 

More information about the Python-Dev mailing list