Top and Bottom Values [PEP: 326]

Peter Otten __peter__ at web.de
Wed Sep 27 06:31:32 EDT 2006


Antoon Pardon wrote:

> I had written my own module, which works similarly but
> is somewhat extended. Here is an example of how it can
> be used and how I would like to use it but get stuck.
> 
> from extreme import Top
>>>> Top
> Top
>>>> Top + 1
> Top
>>>> Top - 30
> Top
>>>> Top > 1e99
> True
>>>> lst = range(10)
>>>> lst[:Top]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: slice indices must be integers or None
> 
> So this is where I am stuck. I need this Top value in
> a context where it can be used as a start or stop value
> in a slice. My idea was that since a stop value greater
> than the length of lst in this context would simply return
> a copy of lst, using Top in such a way should behave so
> too. However I don't see a way of doing that.
> 
> So can someone provide ideas to get this behaviour?

>>> import sys
>>> class Top(object):
...     def __index__(self):
...             return sys.maxint
...
>>> Top = Top()
>>> range(5)[:Top]
[0, 1, 2, 3, 4]

This can of course fail in many interesting ways...

Peter





More information about the Python-list mailing list