Python Forum

Full Version: Native support for array-slicing syntax?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

A newbie question on the 'how' of the array slicing syntax.

Given that,
  1. Python does not support NumPy style arrays natively;
  2. NumPy is a package that you must import;
  3. Imported packages cannot in general extend or modify the syntax of a language;

how is NumPy able to support the colon syntax for slicing?

For example,
Quote:>>> from numpy import *
>>> a = array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ])
>>> a[:, 1:3]
array([[2, 3],
[5, 6],
[8, 9]])
>>>

In other words, if I were to create a NumPy-like package from scratch, what feature of Python would I use to support the colon-based syntax for slicing?

Many thanks.

Regards,
/nxs
I don't know exactly how Numpy does it. But you could do it for your own classes by overriding __getitem__(key) and __setitem__(key, value). Whatever is in the brackets gets passed to those methods as the key parameter. In the example you give, it's a tuple of two slices. But as far as I know, it could be anything. And you could do anything with it. You could have it be the string 'one to five' and write code that would interpret that as 1:5 and return the appropriate slice of whatever.