On Feb 17, 2005, at 23:22, Duncan Child wrote:

I have attached some code that illustrates part of the pain we have experienced developing libraries of algorithms that can handle both arrays and scalars. The attached library is the reusable part. The other part of this problem is that we have lots of logic sprinkled throughout our algorithms to enable them to handle both arrays and scalars.

See comments below...

Secondly, I have just been bitten by this declaration which suggests that the new Numeric might handle default values better:.

_vp_mod = zeros(num_pts)

It would be less surprising to someone developing numeric algorithms if functions like this defaulted to creating a double precision array rather than integers.

If you want a function that returns float arrays, it is trivial to write and adds negligible overhead: def float_array(array_spec): return Numeric.array(array_spec, Numeric.Float) No need to interfere with Numeric's principle of "smallest usable type", which fits well into the Python type promotion hierarchy. More generally, I don't think defaults should be chosen with a particular application in mind. Arrays are a general and widely useful datatype in many domains. I use integer arrays as much as float arrays, even though my applications qualify as "numeric".

""" The following safe_ methods were written to handle both arrays amd scalars to save the developer of numerical methods having to clutter their code with tests to determine the type of the data. """

def safe_take(a,indices): # Slice the input if it is an array but not if it is a scalar

This is a very bad example. Your function does not interpret scalars as rank-0 arrays (for which take() would fail), but as something completely different.

def safe_copy(a): # Return a copy for both scalar and array input

That is a semantically reasonable application, but also one for which a simple and standard solution already exists: copy.copy().

def safe_min(a): # Return the minimum of the input array or the input if it is a scalar

I would argue that this is not a good example either, as "minimum over an array" implies a reduction operation which is not defined for a scalar. On the other hand, the operation you define certainly makes sense.

def safe_len(a): # Return the length of the input array or 1 if it is a scalar

That implies that a scalar is somehow equivalent to a rank-1 array of length 1, which is not the case. Actually, all of your examples look like an attempt to recreate Matlab behaviour. But Python is not Matlab! Konrad. -- --------------------------------------------------------------------- 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: hinsen@llb.saclay.cea.fr ---------------------------------------------------------------------