[Numpy-discussion] new __wrap_array__ magic method

Sebastien.deMentendeHorne at electrabel.com Sebastien.deMentendeHorne at electrabel.com
Thu Aug 11 04:37:17 EDT 2005

> >Hi,
> >
> >Currently, we have an __array__ magic method that can be 
> used to transform any object that implements it into an array.
> >It think that a more useful magic method would be, for 
> ufuncs, a __wrap_array__ method that would return an array 
> object and a function to use after having applied the ufunc.
> >  
> >
> There is an interest in doing this but it is a bit more 
> complicated for 
> ufuncs with more than one input argument and more than one 
> output argument.
> I have not seen a proposal that really works.    Your __wrap_array__ 
> method sounds interesting though.   I think, however, that the 
> __wrap_array__ method would need to provide some kind of 
> array_interfaceable object to be really useful.
> In the new scipy.base, I've been trying to handle some of 
> this, but it 
> is more complicated than it might at first appear.

If we use the same convention as __add__ and __radd__ & co for binary functions this would make a

__wrap_array__(self, ufunc): # all unary operators like __neg__, __abs__, __invert__
__lwrap_array__(self, other, ufunc): # all binary operators called with self on the lhs like __add__, __mul__, __pow__
__rwrap_array__(self, other, ufunc): # all binary operators called with self on the rhs like __radd__, __rmul__, __rpow__

with first a check on __lwrap_array__ and then __rwrap_array__ for binary functions.
Those functions should then return the result of the operation (and not anymore an array object and a "constructor" function.

My previous example would read:
class TimeSerie:
	def __init__(self, data, times):
		self.data = data      # an array
		self.times = times    # anything, could be any metadata

	def __wrap_array__(self, ufunc):
		return TimeSerie( ufunc(self.data) , self.times)

	def __lwrap_array__(self, other, ufunc):
		return TimeSerie( ufunc(self.data, other) , self.times)

	def __rwrap_array__(self, other, ufunc):
		return TimeSerie( ufunc(other, self.data) , self.times)

propagating this way the operation to the other object in binary operations.

Better attempt ?


This message is confidential. It may also be privileged or otherwise protected by work product immunity or other legal rules. If you have received it by mistake please let us know by reply and then delete it from your system; you should not copy it or disclose its contents to anyone. All messages sent to and from Electrabel may be monitored to ensure compliance with internal policies and to protect our business. Emails are not secure and cannot be guaranteed to be error free as they can be intercepted, amended, lost or destroyed, or contain viruses. Anyone who communicates with us by email is taken to accept these risks.


More information about the NumPy-Discussion mailing list