Confused compare function :)

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Thu Dec 6 14:33:51 CET 2012


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 as well, but for other reasons (see below). But basically this is EAFP.


> (loads of them in many libraries and frameworks)
> instead of:
>
>      if k in mydict:
>          do_stuff(mydict[k])

This is LBYL, C-style, not Pythonic.

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.


Thomas



More information about the Python-list mailing list