[Numpy-discussion] metadata and metabehavior for arrays (for scipy.base or Numeric3)

konrad.hinsen at laposte.net konrad.hinsen at laposte.net
Wed Apr 6 07:49:45 EDT 2005

On Apr 6, 2005, at 12:10, Sébastien de Menten wrote:

> However, I disagree with the “pretty straightforward to implement”. In 
> fact, if one wants to inherit most of the functionalities of Numeric, 
> it becomes quite cumbersome. Looking at MA module, I see that it needs 
> to:

It is straightforward AND cumbersome. Lots of work, but nothing 
difficult. I agree of course that it would be nice to improve the 

> An embryo of idea would be to add hooks in the machinery to allow an 
> object to interact with an ufunc. Currently, this is done by calling 
> __array__ to extract a “naked array” (== Numeric.array vs “augmented 
> array”) but the result is then always a “naked array”.
> In pseudocode, this looks like:
>  def ufunc( augmented_array ):
>    if not isarray(augmented_array):
>      augmented_array = augmented_array.__array__()
>    return ufunc.apply(augmented_array)

The current behaviour of Numeric is more like

	def ufunc(object):
		if isarray(object):
			return array_ufunc(object)
		elif is_array_like(object):
			return array_func(array(object))
			return object.ufunc()

A more general version, which should cover your case as well, would be:

	def ufunc(object):
		if isarray(object):
			return array_ufunc(object)
				return object.applyUfunc(ufunc)
			except AttributeError:
				if is_array_like(object):
					return array_func(array(object))
					raise ValueError

There are two advantages:

1) Classes can handle ufuncs in any way they like, even if they 
    array-like objects.
2) Classes must implement only one method, not one per ufunc.

Compared to the approach that you suggested:

> where I would prefer something like
>  def ufunc( augmented_array ):
>    if not isarray(augmented_array):
>      augmented_array, contructor = 
> augmented_array.__array_constructor__()
>    else:
>      constructor = lambda x:x
>    return constructor(ufunc.apply(augmented_array))

mine has the advantage of also covering classes that are not array-like 
at all.

Konrad Hinsen
Laboratoire Léon Brillouin, CEA Saclay,
91191 Gif-sur-Yvette Cedex, France
Tel.: +33-1 69 08 79 25
Fax: +33-1 69 08 82 61
E-Mail: khinsen at cea.fr

More information about the NumPy-Discussion mailing list