[Tutor] random.choice()

Alan Gauld alan.gauld at btinternet.com
Thu Jul 3 03:12:28 CEST 2008


"John Fouhy" <john at fouhy.net> wrote

>>  otherwise. this will be removed for Python 3.x because you can 
>> just
>>  use hasattr(obj, '__call__').

I was about to go BOO HISS because callable() is much more
readable than hasattr() but...

> you can instead say:
>
> try:
>    foo()
> except TypeError:
>    # do something else

This makes slightly more sense, although a TypeError seems a bit
too vague, if it had bveen a CallableError then I'd say fine. With
TypeError we have a much wider chance of a problem, particularly
if the callable takes parameters:

>>> sum('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>

I can see the reason easily interactively but in a try except
its much harder to tell if the Typeerror was due to sum being
non callable or to me giving an invalid argument!

So still a bit of a boo hiss. But at least I can use hasattr within
the handler I suppose.

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list