Issue
If I have a custom python class, and use that in a numpy.ndarray
, my array ends up with dtype 'O' (object), which is fine:
import numpy
class Test(object):
"""Dummy class
"""
def __init__(self, value):
self.value = value
def __float__(self):
return float(self.value)
arr = numpy.array([], dtype=Test)
This gives me array([], dtype=object)
, but how can I unwrap the dtype to check that the underlying type is Test
?
This is easy when there are elements in the array, since I can use isinstance
on any of the members, but when the array is empty, I am stumped. I hope that the underlying type is stored in the dtype somewhere...
Solution
You can't. Arrays aren't meant to be used with non-primitive types (efficiently), and really are no different from a (terribly slow) list. In fact, once you go object, you can put anything you want into the array:
array((Test(),[])) #works fine, dtype object. Even explicitly setting dtype will not fail, and be ignored.
As you can see - if you do not put a primitive numpy
can convert to, no type enforcing is done.
Though I would not recommend an array at all, if you can guarantee the array contains a single type, then
type(arr[0])
is really your only option (which is shape dependent of course).
Answered By - kabanus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.