Indexes and Slices.

Gustavo Cordova gcordova at hebmex.com
Fri Feb 22 10:18:39 EST 2002


Regarding the current (2.2) behaviour of indexes
and slices (you know, array-like behaviour), here's
what I found out today.



## Start up pythonwin.

PythonWin 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au)
 - see 'Help/About PythonWin' for further copyright information.

# Let's first create a simple, gentle class.

>>> class SliceTest:
... 	def __getitem__(self, *args):
... 		print "getitem: %s" % repr(args)
... 	def __setitem__(self, *args):
... 		print "setitem: %s" % repr(args)
... 	def __delitem__(self, *args):
... 		print "delitem: %s" % repr(args)
... 
>>> 

## And now, a simple, gentle object.

>>> st = SliceTest()

## Let's test the waters first.

>>> i = st[10]
getitem: (10,)

## OK, this was expected. Just returned the key
## in a one element tuple.

>>> i = st[10:20]
getitem: (slice(10, 20, None),)

## Neat, the slice notation becomes a slice
## object, which has a third element... why?
## Should I specify a third part to the slice?

>>> i = st[10:20:4]
getitem: (slice(10, 20, 4),)

## Yes, seems like we can say "from 10 to 20, by 4"

>>> # MOST INTERESTING!!

## Indeed.

>>> st[10] = 12
setitem: (10, 12)

## No surprises here.

>>> st[10:23] = "hola"
setitem: (slice(10, 23, None), 'hola')

## Hmmm... slice object again. Lets look further.

>>> st[10:23:3] = "hola"
setitem: (slice(10, 23, 3), 'hola')

## Yep, same behaviour. Neat.

>>> st[12,2] = "hola"
setitem: ((12, 2), 'hola')

## THIS was news.
## Commas in indexes convert the index into a tuple.
## So I can use more complex behaviours, like multi-
## dimensional indexing.

>>> # Hmmm... commas in key argument seem to convert to tuple automagically.

## Yep.

>>> st[12,'a',4] = "Some wierd place in space"
setitem: ((12, 'a', 4), 'Some wierd place in space')

## Nice generalization.
## Very useful, I suppose.

>>> # cool.

## Yes, very.

>>> 

Now, all this is VERY interesting, specially the last
part about automagically converting indexes with commas
in them to tuples.

This will make possible creating true matrix-like behaviours,
instead of hacking it with arrays-of-arrays.

right?
--
Gustavo Córdova Avila
> gcordova at sismex.com
Å 8351-3861 | 8351-3862




More information about the Python-list mailing list