Pythonic way for missing dict keys

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Mon Jul 30 07:59:48 EDT 2007


On Mon, 30 Jul 2007 07:37:05 +0000, Duncan Booth wrote:

> Steven D'Aprano <steve at REMOVE.THIS.cybersource.com.au> wrote:
> 
>> 
>> Instead of doing:
>> 
>> 
>> if callable(function): function()
>> 
>> you should do:
>> 
>> try:
>>     function()
>> except TypeError:
>>     pass
>> 
>> 
>> 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_?)
> 
> The replacement for callable(x) is simply hasattr(x, '__call__').
> Once upon a time it may have been that functions didn't have a __call__ 
> attribute (I haven't checked back on really old Pythons top see if this 
> was the case), but these

Your sentence seems to have run out early :)

Thanks, I didn't know that -- I remember that Back In The Day checking if
something was callable was tricky, because it could be a function, a
method, or a class with __call__. It makes much more sense to make all
callables go through __call__.



>>> Also, what is the replacement of reduce? I think I remember seeing
>>> somewhere that lists comprehension would be (but also remember the
>>> advise that reduce will be quicker).
>> 
>> No, a list comprehension isn't equivalent to reduce(). There is no
>> replacement for reduce().
> <snip>
> There are of course several replacements for specialised uses of reduce: 
> sum, any, all. There is no general purpose replacement, but you can 
> write one in a few lines if you really need it.

True. But writing the same basic algorithm over and over again is about as
far from best practice as you can get without being a PHP programmer.
*wink* Currying is easy to do too, but Python has grown a function
functools.partial() to do it properly. That's as it should be.

(Yes, I know that's a misuse of the term currying, but it's a common one,
and easier than saying "Making a partial function".)


>> It's a shame really. Oh well, maybe it will sneak back in via a
>> functional module, or itertools, or something. What a waste, what a
>> waste.
> 
> I'm sure it will reappear in some other module, but that's the correct
> place for a little used function, not in builtins.

Oh, I would have no problem at all with reduce being banished to the
functtools module. But it's a shame to have to go through the whole PEP
process, and risk Guido saying no.


-- 
Steven.




More information about the Python-list mailing list