[Tutor] Tips

Mark Lawrence breamoreboy at yahoo.co.uk
Wed Jun 18 21:03:09 CEST 2014


On 18/06/2014 15:25, Albert-Jan Roskam wrote:
> ----- Original Message -----
>> From: Alan Gauld <alan.gauld at btinternet.com>
>> To: tutor at 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'
>

What makes you think that you're calling your add function in either 
example above?  In the first you're not calling anything as you've 
missed the brackets.  Even if you add (groan :) them, you'll be trying 
to call an add method for a dict, not your add function.  In the second 
example, you're trying to add 1 to an empty dict, again your function 
doesn't enter into the equation (double groan :)

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection is active.
http://www.avast.com




More information about the Tutor mailing list