[Numpy-discussion] array_arguments decorator

Zachary Pincus zpincus at stanford.edu
Fri Mar 31 18:52:04 CST 2006


Hi folks -

I had seen some talk on this list about the utility of a decorator  
for functions that need to convert their arguments to numpy arrays.  
This would help eliminate boilerplate calls to 'asarray' like:

def distance_squared(a, b):
   a = numpy.asarray(a)
   b = numpy.asarray(b)
   return ((a - b)**2).sum()

Here is a trivial decorator I was thinking of adding to the wiki --  
does this cover enough cases to be useful? In a bigger sense, would  
it be worthwhile to add some decorators like this to numpy itself?  
(I'm not sure I'm in favor of this, since I kind of like smaller APIs  
over bigger ones.)

def array_arguments(f):
   """Wrap a function such that any positional arguments are
   converted into numpy arrays before the function is called."""
   def convert_arg_wrapper(*args, **kwargs):
     array_args = [numpy.asarray(a) for a in args]
     return f(*array_args, **kwargs)
   return convert_arg_wrapper

now distance_squared can look like:
@array_arguments
def distance_squared(a, b):
   return ((a - b)**2).sum()

if using python 2.4, or if not so using:
def distance_squared(a, b):
   return ((a - b)**2).sum()
distance_squared = array_arguments(distance_squared)

Zach




More information about the Numpy-discussion mailing list