Confused compare function :)

Hans Mulder hansmu at xs4all.nl
Thu Dec 6 15:21:22 CET 2012


On 6/12/12 14:58:01, Chris Angelico wrote:
> On Fri, Dec 7, 2012 at 12:33 AM, Thomas Rachel
> <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de>
> wrote:
>> > Am 06.12.2012 09:49 schrieb Bruno Dupuis:
>> >
>>> >> The point is Exceptions are made for error handling, not for normal
>>> >> workflow. I hate when i read that for example:
>>> >>
>>> >>      try:
>>> >>          do_stuff(mydict[k])
>>> >>      except KeyError:
>>> >>          pass
>> >
>> > I would do
>> >
>> >     try:
>> >         value = mydict[k]
>> >     except KeyError:
>> >         pass
>> >     else:
>> >         do_stuff(k)
>> >
>> > Why? Because do_stuff() might raise a KeyError, which should not go
>> > undetected.

> (Assuming first off that you meant "do_stuff(value)", not
> "do_stuff(k)", in that last line)

> That has quite different functionality, though. The original wouldn't
> have called do_stuff at all if k is not in dict, behaviour which is
> matched by both his EAFP and his LBLY. But your version, in the event
> of a KeyError, will call do_stuff with the previous value of value, or
> raise NameError if there is no such previous value. I don't think
> that's intentional.

Errhm, no.  Look again.  The do_stuff(value) call is in the "else:"
clause, so it will only be done of there was no Exception of any
kind, and in that case the assignment to value must have succeeded.

-- HansM



More information about the Python-list mailing list