except clause syntax question
Duncan Booth
duncan.booth at invalid.invalid
Tue Jan 31 17:03:24 EST 2012
Charles Yeomans <charles at declareSub.com> wrote:
> To catch more than one exception type in an except block, one writes
>
> except (A, B, C) as e:
>
> I'm wondering why it was decided to match tuples, but not lists:
>
> except [A, B, C] as e:
>
> The latter makes more sense semantically to me -- "catch all exception
> types in a list" as opposed to "catch this single thing composed of
> three exception types".
>
It may not be the only reason but the code would have to be slower and much
more complex to handle lists.
If you wanted you can write:
except ((A,), ((B,), C)) as e:
or other such complicated expression with nested tuples. If lists were
allowed in a similarly nested structure there would be a danger that you
could pass in a recursive list structure so the code would have to detect
and avoid infinite loops.
exceptions = [A, B, C]
exceptions[1:1] = exceptions,
...
except exceptions as e: # argh!
Abitrarily nested tuples of exceptions cannot contain loops so the code
simply needs to walk through the tuples until it finds a match.
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list