function taking scalar or list argument

Peter Otten __peter__ at web.de
Mon Aug 23 14:27:41 EDT 2004


beliavsky at aol.com wrote:

> 
> I can define a function that transforms either a scalar or each element in
> a list as follows:
> 
> def twice(x):
>     try:
>         return map(twice,x)
>     except:

A bare except without the type of exception is always bad.

>         return 2*x
> 
> print twice(3) # 6
> print twice([1,4,9]) # [2,8,18]
> 
> Is this good style? I intend to define many functions like this and want
> to use the right method. Thanks.
 
I'd say you've just discovered a use case for a decorator:

def scalarOrVector(f):
    def g(arg):
        try:
            return map(f, arg) # or map(g, arg) if you want to allow 
                               # nested sequences
        except TypeError:
            return f(arg)
    return g

#@scalarOrVector
def twice(a):
    return 2*a
twice = scalarOrVector(twice)

print twice(3) # 6
print twice([1,4,9]) # [2,8,18]

Of course you will have to ensure that map(f, arg) _does_ throw an
exception.

Peter





More information about the Python-list mailing list