I am creating a class object which must inherit from numpy ndarray
s. I perform an isinstance
check and an array.shape
check with the __new__
method. Is it alright to have it here, or should it be elsewhere? I saw suggestions to create an exceptions class to accompany it, but it doesn't seem necessary... maybe preferable.
'''
pnts_instantiation.py
'''
import numpy as np
import sys
from types import *
class Points(np.ndarray):
'''ndarray required,info='array info',name='pnts'')
'''
def __new__(cls,arr=None,info=None,name='pnts'):
'''create Points from existing data'''
err = 'Failed...Requires an ndarray...\nProvided: {}'.format(type(arr))
if isinstance(arr,(NoneType,StringType,UnicodeType,ListType,TupleType)):
return err
if arr.shape < (4,2):
return ('Failed...Requires array shape > (4,2)\nProvided: {}'.format(arr.shape))
self = np.asarray(arr).view(cls) # view as Points class
self.info = info # set info
self.name = name # set name
self.applied = None
# other properties not pertinent to discussion removed for simplicity
return self
def __array_finalize__(new_arr, src_arr):
'''new_arr: new Points object...housecleaning takes place
for explicit, view casting or new from template...
src_arr: None, any subclass of ndarray including our own OR another
instance of our own array (see docs)'''
if src_arr is None: return
new_arr.applied = getattr(src_arr,'applied',None) # provide a default
new_arr.name = getattr(src_arr,'name',None)
def __array_wrap__(self,out_arr,context=None):
'''wrap it up'''
return np.ndarray.__array_wrap__(self, out_arr, context)
def __repr__(self):
'''return point info, shape and dtype'''
s = self
st = '==> {}'.format(s)
if (hasattr(s,'name')) and (hasattr(s,'info')):
st = 'name: {}\nshape: {}\ninfo: {}\nvalues:\n{}'.format(s.name,s.shape,s.info,s)
elif (hasattr(s,'name')) and (hasattr(s, 'applied')):
st = '{}.{}: {}'.format(s.name,s.applied, s)
else:
st = '{}: {}'.format(s.applied,s)
return st
def test_cases():
'''conditional case check'''
cases = [None,
'string',
[[1,2],[3,4]],
np.asarray([[1,2],[3,4]],dtype='float64',),
np.ma.asarray([[1,2],[3,4],[5,6]],dtype='float64'),
np.asarray([[1,2],[3,4],[5,6]],dtype='float64'),
np.asarray(zip(np.arange(5),np.arange(5)),dtype='float64')
]
counter = 0
for a_case in cases:
print('\nCase: {}\nIn: {}\nOut: {}'.format(counter,a_case,Points(a_case)))
counter += 1
#-------------------
if __name__ == '__main__':
test_cases()