If this is what you are going to do in a lot of functions, you can use the Python decorator. Here is simple but useful.
def threads_over_lists(fn): def wrapped(x, *args, **kwargs): if isinstance(x, list): return [fn(e, *args, **kwargs) for e in x] return fn(x, *args, **kwargs) return wrapped
This way, just adding the @threads_over_lists line before your function forces it to behave that way. For instance:
@threads_over_lists def add_1(val): return val + 1 print add_1(10) print add_1([10, 15, 20])
You should also consider whether you want this to be vectorized only over lists, as well as over other iterable objects such as tuples and generators. This is a useful StackOverflow question for defining it. However, be careful - the string is repeatable, but you probably won't want your function to work on every character inside it.
source share