range question, compared to Smalltalk

Neal Norwitz neal at metaslash.com
Wed Aug 28 01:00:23 CEST 2002


On Tue, 27 Aug 2002 18:08:09 -0400, Frank Buss wrote:

> Tim Peters <tim.one at comcast.net> wrote:
> 
>>> Looks like "range" returns a normal list.
>> 
>> Right.
>> 
>>> Why not an object?
>> 
>> A list is an object.
> 
> Yes, you're right :-)
> 
> What I mean: Is there any reason, why one shouldn't derive a class from
> the list-class (perhaps called 'interval'), which behaves like a list,
> but has only 2 attributes: start and end value. All methods and
> operators on this object are overloaded, so that it looks like  a list
> for callers, but is much less memory consuming.

Use xrange.  But xrange only works on integer values defined by a C long
(usually 32 bits, but sometimes 64 bits).

> As I said, I'm a beginner in Python, but here are a start of such a
> class and the range re-definition:
> 
> class Interval:
>   def __init__(self, start, end):
>     self.start = start
>     self.end = end
>   def __getitem__(self, index):
>     return self.start + index
> def range(start, end):
>   return Interval(start, end)
> 
> i = range(123456, 123456789012)
> print i[12345678901]
> result: 12345802357

Slightly modified (to fit in 32 bits):

>>> i = xrange(123456, 123456789)
>>> print i[12345678]
12469134

> There are much more operators and methods missing, but it should be
> possible, shouldn't it? Are there any conflicts or performance hits with
> existing code, if someone would implement it as standard Python?
> 
> BTW: is there a way to re-define the builtin range?

>>> import __builtin__
>>> def myrange(a, b):    
...   print 'hi'
...   return xrange(a, b)
... 
>>> __builtin__.range = myrange
>>> range(1, 2)
hi
xrange(1, 2)

> Another question: Why isn't it possible to get attributes from ints, but
> from strings?
> 
>>>> 3.__class__
>   File "<stdin>", line 1
>     3.__class__
>               ^
> SyntaxError: invalid syntax
>>>> "abc".__class__
> <type 'str'>
 
3.__class__ is parsed as a float:

>>> 3..__class__
<type 'float'>
>>> 3 .__class__
<type 'int'>
>>> '3'.__class__
<type 'str'>

HTH,
Neal



More information about the Python-list mailing list