Pythonic way for missing dict keys
Duncan Booth
duncan.booth at invalid.invalid
Mon Jul 30 03:37:05 EDT 2007
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
>> 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.
>
> 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.
More information about the Python-list
mailing list