public
Created

Some example code showing unexpected behavior of __array_wrap__ in a subclass of np.matrix

  • Download Gist
matrix_array_wrap_test.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
import numpy as np
 
class ArrSubClass(np.ndarray):
def __new__(cls, input_var):
obj = np.ndarray(input_var).view(cls)
return obj
def __array_wrap__(self, obj):
raise AssertionError
 
class MatSubClass(np.matrix):
def __new__(cls, input_var):
obj = np.matrix(input_var).view(cls)
return obj
def __array_wrap__(self, obj):
raise AssertionError
 
def run_test(obj_creation_strs = ['o=ArrSubClass(2)',
'o=MatSubClass([1, 1])',
'o=MatSubClass([1.0, 1.0])',],
obj_use_strs = ['o2 = o + 2', 'o2 = o + 2.0',
'o2 = o * 2', 'o2 = o * 2.0',
'o2 = o * o.T',
'o2 = np.dot(o,2)',
'o2 = np.dot(o,2.0)',
'o2 = np.dot(o,o.T)',
'o2 = np.core.multiarray.dot(o,2)',
'o2 = np.core.multiarray.dot(o,2.0)',
'o2 = np.core.multiarray.dot(o,o.T)'] ):
 
str_fmt = '{0:10s} | {1:30s} | {2:20s}'
print str_fmt.format('aw called?', 'creation', 'use')
for create_str in obj_creation_strs:
print
for use_str in obj_use_strs:
exec(create_str)
try:
exec(use_str)
except AssertionError:
print str_fmt.format('Yes', create_str, use_str)
else:
print str_fmt.format('No', create_str, use_str)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.