function taking scalar or list argument

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


beliavsky <at> aol.com <beliavsky <at> 127.0.0.1> writes:
> def twice(x):
>     try:
>         return map(twice,x)
>     except:
>         return 2*x
> 
[snip]
> Is this good style?

First a general comment about catching exceptions -- you should probably write 
your try-except block as:

try:
    ...
except TypeError:
    ...

Better to only catch the exceptions that your call to map will throw.


But to really answer your question, I would probably avoid this style.  It 
means for every number you double (whether an element of a list, or an element 
alone), you'll throw and catch an exception.  This needlessly complicates the 
simple case.  Exception handling is intended to deal with "exceptional" cases, 
cases which should be relatively infrequent.  And while Python's exception 
handling is pretty efficient, it's still not particularly cheap to catch 
exceptions.  You would probably be better with:

def twice(x):
	if isinstance(x, list):
		return map(twice, x)
	else:
		return 2*x

In this case, instead of incurring the cost of a thrown and caught exception 
for each number, you incur only the cost of a isinstance test.  You also avoid 
treating the common case as the exceptional one.

Steve

P.S.  In reality, I probably wouldn't write a method like this, instead 
relying on the caller to call map for themselves if necessary.  The caller is 
much more likely to know the type of the object they want to double anyway, so 
they may not even need to use the isinstance test.




More information about the Python-list mailing list