[Python-Dev] An ability to specify start and length of slices

Nick Coghlan ncoghlan at iinet.net.au
Fri Jun 4 09:53:39 EDT 2004

Noam Raphael wrote:

> Two examples:

Both examples you give are far more self-explanatory if you use 
temporary variables to create self-documenting code rather than trying 
to squeeze everything in to one line. Particularly since using magic 
numbers in your code is generally evil, anyway.

(The X's in the code examples are just so they don't look like quoted 
sections to Thunderbird and other mail clients)

> 1. Say I have a list with the number of panda bears hunted in each 
> month, starting from 1900. Now I want to know how many panda bears were 
> hunted in year y. Currently, I have to write something like this:
> sum(huntedPandas[(y-1900)*12:(y-1900)*12+12])
> If my suggestion is accepted, I would be able to write:
> sum(huntedPandas[(y-1900)*12:>12])

X >>> y_jan = (y-1900)*12
X >>> sum(huntedPandas[y_jan:y_jan+12])

> 2. Many data files contain fields of fixed length. Just an example: say 
> I want to get the color of the first pixel of a 24-bit color BMP file. 
> Say I have a function which gets a 4-byte string and converts it into a 
> 32-bit integer. The four bytes, from byte no. 10, are the size of the 
> header, in bytes. Right now, if I don't want to use temporary variables, 
> I have to write:
> picture[s2i(picture[10:14]):s2i(picture[10:14])+4]
> I think this is nicer (and quicker):
> picture[s2i(picture[10:>4]):>4]

X >>> header_size = s2i(picture[10:14])
X >>> first_pixel = picture[header_size:header_size+4]

I don't see any reason to change Python to encourage the writing of code 
which is significantly more cryptic as it tries to cram too much onto 
one line.

The only reason I can see for not wanting to use temporary variables is 
if you're using some part of the language that demands an expression 
(e.g. a lambda or a generator expression). But if you're talking about 
embedding this sort of thing inside an *additional* level of expression, 
it's just going to get even *more* unreadable, and it may be time to 
bite the bullet and write a helper function to get the info you want.

If you want extremely concise, but entirely unreadable code, there's 
another language beginning with P that you can use ;)

(you may want to think about submitting a patch that just adds a method 
to lists: list.length_slice(slice_start, slice_length). You'd probably 
need a better name than the one I just used, though)


Nick Coghlan               |     Brisbane, Australia
Email: ncoghlan at email.com  | Mobile: +61 409 573 268

More information about the Python-Dev mailing list