slice notation as values?
Steven Bethard
steven.bethard at gmail.com
Sat Dec 10 16:13:35 EST 2005
Antoon Pardon wrote:
> On 2005-12-10, Steven Bethard <steven.bethard at gmail.com> wrote:
>
>>Antoon Pardon wrote:
>>
>>>So lets agree that tree['a':'b'] would produce a subtree. Then
>>>I still would prefer the possibility to do something like:
>>>
>>> for key in tree.iterkeys('a':'b')
>>>
>>>Instead of having to write
>>>
>>> for key in tree['a':'b'].iterkeys()
>>>
>>>Sure I can now do it like this:
>>>
>>> for key in tree.iterkeys('a','b')
>>>
>>>But the way default arguments work, prevents you from having
>>>this work in an analague way as a slice.
>>
>>How so? Can't you just pass the *args to the slice contstructor? E.g.::
>>
>> def iterkeys(self, *args):
>> keyslice = slice(*args)
>> ...
>>
>>Then you can use the slice object just as you would have otherwise.
>
> This doesn't work for a number of reasons,
>
> 1)
>>>>slice()
>
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: slice expected at least 1 arguments, got 0
I wasn't sure whether or not the slice argument was optional.
Apparently it's intended to be, so you have to make one special case:
def iterkeys(self, *args):
keyslice = args and slice(*args) or slice(None, None, None)
> 2) It doens't give a clear way to indicate the following
> kind of slice: tree.iterkeys('a':). Because of the
> follwing:
>
>>>>slice('a')
> slice(None, 'a', None)
>
> which would be equivallent to tree.iterkeys(:'a')
Well, it certainly gives a way to indicate it:
tree.iterkeys(None, 'a')
Whether or not it's a "clear" way is too subjective of a topic for me to
get into. That's best left to Guido[1]. My point is that it *does*
work, and covers (or can be slightly altered to cover) all the
functionality you want. That doesn't mean you have to like the API for
it, of course.
STeVe
[1] By which I mean that you should submit a PEP on the idea, and let
Guido decide which way is prettier. Just be sure to give all the
equivalent examples - i.e. calling the slice constructor with the
appropriate arguments.
More information about the Python-list
mailing list