开发者

Python extented slicing with lists: is the documentation correct?

The docs at http://docs.python.org/reference/expressions.html#slicings say (with some excerpts):

5.3.3. Slicings

A slicing selects a range of items in a sequence object (e.g., a string, tuple or list).

slicing          ::=  simple_slicing | extended_slicing
simple_slicing   ::=  primary "[" short_slice "]"
extended_slicing ::=  primary "[" slice_list "]"
slice_list       ::=  slice_item ("," slice_item)* [","]
slice_item       ::=  expression | proper_slice | ellipsis
proper_slice     ::=  short_slice | long_slice
short_slice      ::=  [lower_bound] ":" [upper_bound]
long_slice       ::=  short_slice ":" [stride]
lower_bound      ::=  expression
upper_bound      ::=  expression
stride           ::=  expression
ellipsis         ::=  "..."

The semantics for a simple slicing are as follows. The primary must evaluate to a sequence object...

The semantics for an extended slicing are as follows. The primary must evaluate to a mapping object, ...

The question:

To support [1,2,3][a:b:c] notation the language reference requires lists to be mapping objects (the stride is there only with "extended slicing", which is for mapping objects). So, is the language reference broken (may be they just forgot to update it upon introduction of What's New in Python2.3: Extended Slices ?)?

Also, slicing is obviously not only for sequence objects (see the first phrase above).

Or is it just me? ;)

P.S.

Interestingly, Python 3 docs at http://docs.python.org/release/3.1.3/reference/expressions.html#slicings say:

A slicing selects a range of items in a sequence object (e.g., a string, tuple or list)...

["unified" slicing definition, not differentiating between "exteneded" and "simple" here]

The sema开发者_JAVA百科ntics for a slicing are as follows. The primary must evaluate to a mapping object, ...


The language about a mapping is broken; it should say 'sequence or mapping' in all cases to match the behaviour of the interpreter. Both protocols can accept slice objects, and the interpreter will do the conversion in all cases. However, for the built-in types, only the sequences actually support it:

 >>> a = {'a': 1, 'c': 2}
 >>> a['a':'b']
 Traceback (most recent call last):
   File "<pyshell#32>", line 1, in <module>
     a['a':'b']
 TypeError: unhashable type: 'slice'

Note that this is the dictionary complaining that a slice isn't a valid key, not the interpreter complaining that you can't do a slice on a mapping. Which makes sense - dictionaries have no implied ordering of their keys, and so it is unclear what a slice should mean.


What's New and the langref are, unfortunately, using two different definitions of "extended slicing". Both documents are correct for their respective definitions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜