[Numpy-discussion] Use my own data type with NumPy
Wed Sep 5 14:28:49 CDT 2007
Günter Dannoritzer wrote:
> 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.
Yes, I believe we've explained why this is the case and how to work around it.
You can encapsulate that workaround into a function specifically for making
arrays of FixedPoint objects, if you like.
> Would creating my own dType solve that problem?
No. That's only useful for C data types, not Python instances. You're pretty
much stuck with object arrays.
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Numpy-discussion