Re: Implementing variable number of option arguments

Beni Cherniavsky <[email protected]> Fri, 12 Nov 2004 15:15:39 +0200
Newsgroups gmane.comp.python.optik.user
Message-ID <[email protected]>
Greg Ward wrote:
> 
> [rummage ... dig ... read ...]  Hmmm!  I did not know that these:
> 
>   somelist[5:]
>   somelist[5:None]
> 
> were equivalent!  But here's something weird: if I write a subclass of
> list, eg.
> 
> class mylist(list):
>   def __getslice__(self, a, b):
>     print a, b
>     return super(mylist, self).__getslice__(a, b)
> 
> it reveals that
> 
>   somelist[5:]
> 
> actually calls
> 
>   somelist.__getslice__(5, 2147483647)
> 
This is retained for backward compatibility.  `__getslice__` has been 
deprecated for quite some time in favor of letting `__getitem__` handle 
slice objects and/or tuple of slice objects:

 >>> class yourlist(list):
...     def __getslice__(self, *args):
...         print args
...         return super(yourlist, self).__getslice__(*args)
...
 >>> mylist(range(5))[2:]
(2, 2147483647)
[2, 3, 4]
 >>> class mylist(list):
...     def __getitem__(self, *args):
...         print args
...         return super(mylist, self).__getitem__(*args)
...
 >>> mylist(range(5))[2:]
[2, 3, 4]
 >>> # Inheriting from `list` was a bad example.  `list.__getslice__` is
... # called before `mylist.__getitem__` has a chance.
...
 >>> class mylist(object):
...     def __getitem__(self, *args):
...         print args
...
 >>> mylist()[2:]
(slice(2, None, None),)

See `Additional methods for emulation of sequence types`__ and 
`Emulating container types`__ for details.

__ http://www.python.org/dev/doc/devel/ref/sequence-methods.html
__ http://www.python.org/dev/doc/devel/ref/sequence-types.html

Unfortunately in `Slicings`__ it confusingly says:

     [...]  Similarly, when the slice list has exactly one short slice
     and no trailing comma, the interpretation as a simple slicing takes
     priority over that as an extended slicing.

     The semantics for a simple slicing are as follows. The primary must
     evaluate to a sequence object. The lower and upper bound
     expressions, if present, must evaluate to plain integers; defaults
     are zero and the sys.maxint, respectively.  [...]

     The semantics for an extended slicing are as follows.  [...]

     __ http://www.python.org/dev/doc/devel/ref/slicings.html

This is pretty confusing.  It should say clearly that these rules apply 
for built-in types; for custom types it depends on the methods 
implemented with the "simple slicing" methods being deprecated.

I'll try to file a python doc bug when I find a good re-formulation...



-------------------------------------------------------
This SF.Net email is sponsored by:
Sybase ASE Linux Express Edition - download now for FREE
LinuxWorld Reader's Choice Award Winner for best database on Linux.
http://ads.osdn.com/?ad_id=5588&alloc_id=12065&op=click