function taking scalar or list argument

Jeff Shannon jeff at ccvcorp.com
Tue Aug 24 01:57:19 CEST 2004


Larry Bates wrote:

>You may want to take a look at isinstance() function.
>
>def twice(x):
>    if isinstance(x, list): return map(twice, x)
>    if isinstance(x, (int, float, str)): return 2*x
>    return None
>  
>

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.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list