----- Original Message ----- > From: Alan Gauld <alan.ga...@btinternet.com> > To: tutor@python.org > Cc: > Sent: Wednesday, June 18, 2014 11:47 AM > Subject: Re: [Tutor] Tips > > On 18/06/14 01:15, Nanohard wrote: >>> On 2014-06-17 13:35, Alan Gauld wrote: >>> >>>> Don't test types, use the interface >>> >>> Can you please explain what you mean by this? >> >> He means use the Python interpreter, by going to your console and typing > "python", or in Windows >> it's called 'IDLE'. > > > Nope, I meant what Mark and Danny said. > > For example don't do this: > > def add(a,b): > if type(a) == int and type(b) == int: > return a+b > else: > raise TypeError > > 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 Btw, given that: >>> {}.__add__ Traceback (most recent call last): File "", line 1, in AttributeError: 'dict' object has no attribute '__add__' Why does one only need to use 'except TypeError', not 'except (TypeError, AttributeError)' in the try-except above? >>> {} + 1 Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'dict' and 'int' _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor