Vectorized functions

Steven D'Aprano steve+python at pearwood.info
Thu Aug 11 00:02:05 EDT 2016


Its sometimes very useful to apply a function to each element of a list in
turn. One common term for that is "vectorized function".

Julia has a convenient syntactic shortcut for this:

http://julia.readthedocs.io/en/latest/manual/functions/#dot-syntax-for-vectorizing-functions

    func(arg)

calls func with a single argument, "arg", while:

    func.(arg)

expects "arg" to be an array of values, and returns a new array generated by
calling func(x) for each element x in the array. That's equivalent to the
list comprehension and functional syntax:

    [func(x) for x in arg]
    map(func, arg)


Here's a neat little decorator which decorates a function with a special
callable attribute "v" which operates somewhat like Julia's dot syntax:

def vectorize(func):
    def v(seq, **kw):
        return [func(x, **kw) for x in seq]
    func.v = v
    return func



py> @vectorize
... def add2(x):
...     return x+2
...
py> add2.v([100, 200, 300, 400])
[102, 202, 302, 402]



This version is just a minimal toy: it always returns a list, regardless of
the input argument. As such it doesn't offer much more than a list
comprehension or map(). I have a more complex version which behaves more
like Python 2's map() in that it tries to return an object of the same type
as its input (e.g. a string if you call it on a string, a tuple if you call
it on a tuple, etc).

Is there any other functionality which would make this more useful?





-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list