slice notation as values?

Antoon Pardon apardon at forel.vub.ac.be
Fri Dec 9 09:19:47 EST 2005


Op 2005-12-09, Duncan Booth schreef <duncan.booth at invalid.invalid>:
> Antoon Pardon asked:
>
>
>> 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.
>
> Quite right, but the syntax for the slice only applies inside the square 
> brackets and there would be big problems making it work outside a 
> subscript. If you allowed a:b you get syntactic ambiguities: e.g. is this a 
> slice or a complete if statement:
>
>    if a:b
>
> If you allow a slice on its own but require the square brackets still to be 
> there then you don't (I think) get any syntax ambiguities, but the result 
> looks like it should be some weird list comprehension so its just too 
> confusing:
>
>    myslice = [a:b]

I don't see the problem. The syntax for tuples can create syntactic
ambiguities too. Take the following statement:

  f(a,b)

Does the call have two parameters or one that is a tuple? In practice
one uses parenthesis to disambigue the stament. So in the above case
it would be a complete if statement. And myslice = a:b wouldn't
cause a problem.

> I think the case for freestanding slices is there, but they aren't common 
> enough to justify special syntax.
>
>> 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'):
>> 
>
>>>> import this
> ...
> There should be one-- and preferably only one --obvious way to do it.
> Although that way may not be obvious at first unless you're Dutch.
> ...
>
> If the user can write
>
>    for key in tree['a':'b']:
>
> then he can write:
>
>    for key in tree['a':'b'].iteritems():

No he can't. tree['a':'b'] would provide a list
of keys that all start with an 'a'. Such a list
doesn't have an iteritems method. It wouldn't even
contain the information to construct items.

-- 
Antoon Pardon



More information about the Python-list mailing list