[Numpy-discussion] Use my own data type with NumPy

Günter Dannoritzer dannoritzer@web...
Wed Sep 5 14:19:58 CDT 2007


Christopher Barker wrote:
> 
[...]
> The solution is to make an empty object array first, then populate it. 
[...]
> 
> Does that help?

Robert, Chris, thanks for that explanation. I understand that now.

The purpose of my (Python) class is to model a fixed point data type. So
I can specify how many bits are used for integer and how many bits are
used for fractional representation. Then it should be possible to assign
a value and do basic arithmetic with an instance of that class. The idea
is that based on fixed point arithmetic rules, each operation tracks
changes of bit width.

I would now like to use that class in connection with numpy and my
question is, whether there is a way to make its use as intuitive as
possible for the user. Meaning that it would be possible to create a
list of my FixedPoint instances and then assign that list to a numpy array.

I created some minimal code that shows the behavior:

import numpy

class FixPoint(object):
  def __repr__(self):
    return "Hello"

  def __len__(self):
    return 3

  def __getitem__(self, key):
    return 7



if __name__ == '__main__':
  a = numpy.array([FixPoint(), FixPoint()])
  print "a: ", a

  b = [FixPoint(), FixPoint()]
  print "b: ", b


When running that code, the output is:

a:  [[7 7 7]
 [7 7 7]]
b:  [Hello, Hello]

What is interesting, the list uses the representation of the class,
whereas array changes it to a list of the indexed values.

Note that when changing the __len__ function to something else, the
array also uses the __repr__ output.

Would creating my own dType solve that problem?

Cheers,

Guenter






More information about the Numpy-discussion mailing list