2008-06-26

Auto Vectorize Decorator


def vectorize(f):
"""
Allows a traditionnal python function to be called with
iterables arguments.

So when you call func([array]) it will do the iteration for you,
call func() for each element in array, and return an array.

All arguments must be iterable, if you want to pass something else,
use a keyword argument.

"""
def _vectorize(*args, **kwargs):
if not isiterable(args[0]):
return f(*args, **kwargs)
else:
return [f(*arg, **kwargs) for arg in zip(*args)]
return _vectorize

# to use it:

@vectorize
def my_func(arguments):
# do something interesting, on ONE element.

my_func(my_args)
my_func(my_super_list_of_many_values)


2 commentaires:

Marco Dinacci said...

isn't that mostly the same as map() ?

# do something on one elem
def my_func(val):
val *=2
return val

>>> a = range(10)
>>> a
[0,1,2,3,4,5,6,7,8,9]
>>> map(my_func,a)
[0,2,4,6,8,10,12,14,16,18]

?

Gautier Portet said...

It does exactly the opposite in fact.
The function and the calling code are the same whatever you are passing to the function.

for example:

def square(x):
return x*x

>>> square(2)
4

# ok ?

# now the magic part !
square = vectorize(square)
>>> square([2,3,4])
[4, 9, 16]

# well it's useless, I know :)
# it was used to interface regular and numeric python...