function taking scalar or list argument

Steven Bethard steven.bethard at gmail.com
Mon Aug 23 23:40:14 EDT 2004


Jeff Shannon <jeff <at> ccvcorp.com> writes:
> Actually, I'd favor the try/except approach.  It's entirely reasonable 
> to think that, if this function might be passed either scalars or lists, 
> it may also be passed a non-list-based sequence object.  If you simply 
> try using map(), then it'll work correctly for any object that follows 
> the expected protocol, regardless of whether that object is (a subclass 
> of) list.  By explicitly demanding a list, you're needlessly limiting 
> the usefulness of the function.

Well, you can always test for the protocol, e.g.:

def twice(x):
    if hasattr(x, "__iter__"):
        return map(twice, x)
    else:
        return 2*x

It just seems like a misuse of the construct to me to treat the most frequent 
case as an exceptional one.  Note that the following solution (that doesn't 
recurse) wouldn't be unreasonable if you expected to pass mostly sequences to 
the function:

def twice(x):
    try:
        return map(lambda x: 2*x, x)
    except TypeError:
        return 2*x

The difference here is that we are now treating the sequence case as the 
simple case -- if we're dealing with a sequence, no exception handling is 
required.  So if the sequence case is substantially more frequent, this would 
be a perfectly reasonable solution.  (Note that the difference between this 
and the original solution is that this version does not recurse, so, unlike 
the original solution, this one will not throw an exception for every element 
in the sequence.)

Steve




More information about the Python-list mailing list