Pythonic way for missing dict keys

Alex Popescu nospam.themindstorm at gmail.com
Thu Aug 2 10:18:30 CEST 2007


Bruno Desthuilliers <bdesth.quelquechose at free.quelquepart.fr> wrote in
news:46b0ed0b$0$2257$426a74cc at news.free.fr: 

> Steven D'Aprano a écrit :
> (snip)
> 
>> Instead of doing:
> 
>> if callable(function): function()
>> 
>> you should do:
>> 
>> try:
>>     function()
>> except TypeError:
>>     pass
> 
> There are time where you may want to know if you have a callable
> without calling it...
> 
>> That should work for most uses of callable(), but isn't quite the
>> same. (What if function() has side-effects, or is expensive, and you
>> want to determine if it is callable, but not actually call it _now_?)
> 
> Indeed.
> 
> The 'correct' replacement would be:
> 
> if hasattr(obj, '__call__'):
>    # it's a callable
> 
> but I don't find it so Pythonic to have to check for a __magic__
> method. 
> 
> 

It looks like Python devs have decided it is Pythonic, because it is 
already in the PEP. Same for execfile and the others. And I am not 
arguing pro or con. I was just wondering about the reasons, as I haven't 
been able to find anything (neither here nor on the dev group).

bests,
./alex
--
.w( the_mindstorm )p.




More information about the Python-list mailing list