The Most Diabolical Python Antipattern

Ian Kelly ian.g.kelly at gmail.com
Fri Jan 30 04:17:11 EST 2015


On Fri, Jan 30, 2015 at 2:02 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Mark Lawrence <breamoreboy at yahoo.co.uk>:
>
>> On 30/01/2015 06:16, Marko Rauhamaa wrote:
>>> How about:
>>>
>>> ==============================
>>>      try:
>>>          do_interesting_stuff()
>>>      except ValueError:
>>>          try:
>>>              log_it()
>>>          except:
>>>              pass
>>>          raise
>>> ==============================
>>>
>>> Surprisingly this variant could raise an unexpected exception:
>>>
>>> ==============================
>>>      try:
>>>          do_interesting_stuff()
>>>      except ValueError:
>>>          try:
>>>              log_it()
>>>          finally:
>>>              raise
>>> ==============================
>>>
>>> A Python bug?
>>
>> It depends on the Python version that you're running - I think!!!  See
>> https://www.python.org/dev/peps/pep-3134/
>
> TL;DR
>
> My Python did do exception chaining, but the problem is the surface
> exception changes, which could throw off the whole error recovery.
>
> So I'm thinking I might have found a valid use case for the "diabolical
> antipattern."

I suppose, although it seems awfully contrived to me. In any case it
would still be better with "except Exception" rather than the bare
except. Unless re-raising that ValueError is more important to you
than letting the user hit Ctrl-C during the logging call.



More information about the Python-list mailing list