Home

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.


>>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().
>
> Guido has essentially done the functional equivalent of deciding that
> because he personally doesn't like for loops, they can and should be
> written out as:
>
> counter = 0
> while counter < len(sequence):
> item = sequence[counter]
> do_something_with_item
> counter += 1
>
> because it is "easier to read" than a for loop.
>
> And yes, if you think my example is extreme because nobody would be that
> stupid, that's the point: removing reduce() _is_ that stupid (and it is
> not often I say that about a language design decision by Guido!). Python
> can, and probably will, get away with it only because reducing an iterable
> to a single value is an uncommon operation, and the most common uses of it
> (summing a sequence, finding the minimum and maximum) already have
> workable replacements.
>
> It's especially stupid because map() and filter(), both of which do have
> simple, easy to understand, completely functional replacements, are going
> to stay. reduce() doesn't, and it is going. That's nuts.

InMyArms(TM) !

(Guido, if you read us...)

previous
next

Re: startswith( prefix[, start[, end]]) Query
Re: An ordered dictionary for the Python library?
Re: unexpected behavior: did i create a pointer?
Re: Latest models of Gibson guitars
Re: proper form for const version of operator->
Fundacja Avalon
Podaruj Zycie
Akogo
Mam Marzenie
Kidprotect