[Tutor] Tips

Alan Gauld alan.gauld at btinternet.com
Wed Jun 18 18:31:46 CEST 2014


On 18/06/14 15:25, Albert-Jan Roskam wrote:

>> Just do this:
>>
>> def add(a,b):
>>       return a+b
>
> Given that the concept of Ducktyping has already been mentioned, is there a reason why you did not mention try-except?
>
> def add(a, b):
>      try:
>          return a + b
>      except TypeError:
>          raise

Because that's a lot of work for no value.
Catching an exception simply to raise it again is
a pointless exercise. Only catch stuff you intend
to process.

Of course an add function is a waste of space too
since one already exists in the operators module
and the + sign is usually all thats needed.
But the function was only an example...

but try/except is completely orthogonal to the
original 'tip' of not checking types.

> Why does one only need to use 'except TypeError',
 > not 'except (TypeError, AttributeError)' in the try-except above?

I'm not sure I understand? You created the try/except.
You can catch as much or as little as you wish.
Leaving it to Python catches both.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list