Skip to content

Instantly share code, notes, and snippets.

@aronnem
Created December 22, 2011 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aronnem/1511354 to your computer and use it in GitHub Desktop.
Save aronnem/1511354 to your computer and use it in GitHub Desktop.
Some example code showing unexpected behavior of __array_wrap__ in a subclass of np.matrix
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment