Top and Bottom Values [PEP: 326]

Antoon Pardon apardon at
Thu Sep 28 11:29:58 CEST 2006

On 2006-09-28, Georg Brandl <g.brandl-nospam at> wrote:
> Antoon Pardon wrote:
>> On 2006-09-27, OKB (not okblacke) <brenNOSPAMbarn at> wrote:
>>> Antoon Pardon wrote:
>>>> To begin with this already fails:
>>>>>>> for i in xrange(Top):
>>>> ...   print i
>>>     	What do you expect this to do?  Loop forever?
>> Yes that is what I would expect.
> For unterminating loops, use while 1:, and if you need the counter,
> itertools.count().

Neither of these will work if you want an easy way to choose
between repeating a specific number of times and an infinite

Of course you can include special tests in your code, but the
purpose of values like Top is to eliminate special case code
in a number of situations.

>> If someone would ask me
>> to implement a function like xrange it would look something
>> like the following (*)
>>   def xrange(start=1, stop, step=1):
>>     while start < stop:
>>       yield start
>>       start += step
>> Since Top is supposed to be bigger than any other value this would
>> indeed loop forever. The only reason that this doesn't work with
>> the builtin, is because the builtin xrange insist on its arguments
>> being ints instead of allowing duck typing.
> xrange() *could* be implemented as shown above, but do you realize
> that it would be a severe performance hit compared to the current
> implementation, which doesn't give almost all users a benefit at all?

That code was just meant to illustrate behaviour, one could always
code as follows:

  def _xrange(start=1, stop, step=1):

    # see implemantation above

  def xrange(start=1, stop, step=1):

    if (type(start), type(stop), type(step)) == (int, int, int):
      return builtin.xrange(start, stop, step)
      return _xrange(start, stop, step)
Just to show that with some thinking one could come up with
an implementation that was fast in most cases and yet would
allow for other types than ints if that would make sense.

Antoon Pardon

More information about the Python-list mailing list