[Tutor] Tips

Albert-Jan Roskam fomcl at yahoo.com
Wed Jun 18 21:17:38 CEST 2014



----- Original Message -----

> From: Mark Lawrence <breamoreboy at yahoo.co.uk>
> To: tutor at python.org
> Cc: 
> Sent: Wednesday, June 18, 2014 9:03 PM
> Subject: Re: [Tutor] Tips
> 
> 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 :)

If I call my add function, then then the return statement would be equivalent to:
-... if a={] and b=[1]: a.__add__(b)
-... if a={} and b=1: AttributeError, because the class dict does not have an __add__ method.
That's why I thought an AttributeError would also have to be caught, just in case the caller is stupid enough to give a dict as the first argument. But indeed (Alan) it was silly of me to just 'raise' and not doing anything else with it.


More information about the Tutor mailing list