slice notation as values?

Antoon Pardon apardon at forel.vub.ac.be
Fri Dec 9 08:01:25 EST 2005


Op 2005-12-09, Duncan Booth schreef <duncan.booth at invalid.invalid>:
> Antoon Pardon wrote:
>
>> Will it ever be possible to write things like:
>> 
>>   a = 4:9
>>   for key, value in tree.items('alfa.': 'beta.'):
>
> The first of these works fine, except you need to use the correct syntax:

Sure, I know that. But why a different syntax?

If we have lst = range(10), we can write

   lst[slice(3,7)]

instead of

   lst[3:7]

Now my impression is that should we only have the upper notation, slices
would be less usefull, because it would make using them more cumbersome.

I think that having this easy notation for slices available in more
general circumstances, would make the use of them in other situations
more easy too.

>>>> a = slice(4,9)
>>>> range(10)[a]
> [4, 5, 6, 7, 8]
>>>> 
>
> The second also works fine, provide tree is a type which supports it and 
> you rewrite the call as tree.items(slice('alfa','beta.')) or perhaps 
> tree['alfa':'beta.'].items(). To support slicing directly on a dictionary 
> you could do:

>>>> class sliceable(dict):
>     def __getitem__(self, item):
>         if isinstance(item, slice):
> 	    return self.__class__((k,v) for (k,v) in self.iteritems()
>                 if item.start <= k < item.stop)
>         return dict.__getitem__(self, item)
>
>>>> d = sliceable({'alpha': 1, 'aaa': 2, 'beta': 3, 'bee': 4 })
>>>> d['alpha':'beta']
> {'alpha': 1, 'bee': 4}
>>>> d['alpha':'beta.']
> {'alpha': 1, 'beta': 3, 'bee': 4}
>>>> for key, value in d['alpha':'beta.'].items():
> 	print key, value
> 	
> alpha 1
> beta 3
> bee 4
>
> It seems unlikely that this will make it into the builtin dict type, but 
> you never know.

It doesn't need to be in the buildin dict type, I just would think it
could make the interface to my own treedict type more intuitive.

In my treedict the keys are accessible in order. If you have dictionary
with strings as keys doing:

  for key in tree:

will give you the keys in alfabetical order. Doing

  for key in tree['a':'b']:

will give you all the keys that start with an 'a'.

Now there are a number of methods with similar results.
keys, values, items and there iter variants iterkeys,
itervalues and iteritems. These methods are 'sliceable'
too and I think the possibilty of giving such a method
a slice as parameter, with the same notation as in
a subscript, would be the clearest way for the user
to provide slice information.

If the user can write:

  for key in tree['a':'b']:

Why shouldn't he be able to write:

  for key, value in tree.iteritems('a':'b'):

-- 
Antoon Pardon



More information about the Python-list mailing list