What's the use of the else in try/except/else?

ma mabdelkader at gmail.com
Thu May 14 07:19:50 CEST 2009


That's great to know! Thanks for that explanation, I am refactoring
something and I was going to make ample use of assertion as I thought
it was the same as C's assertion without the NDEBUG flag.


On Thu, May 14, 2009 at 1:03 AM, Steven D'Aprano
<steven at remove.this.cybersource.com.au> wrote:
> On Thu, 14 May 2009 00:39:35 -0400, ma wrote:
>
>> A really great use for try/except/else would be if an object is
>> implementing its own __getitem__ method, so you would have something
>> like this:
>>
>> class SomeObj(object):
>>     def __getitem__(self, key):
>>               try:
>>                       #sometype of assertion here based on key type
>>               except AssertionError, e:
>>                       raise TypeError, e #invalid type
>
> Why raise AssertionError only to catch it and raise TypeError? Why not
> just raise TypeError in the first place?
>
>
> If you're thinking of writing this:
>
> assert isinstance(key, whatever)
>
> you should be aware that when Python is run with the -O flag (optimize),
> all asserts are disabled, and so your error checking code will not run
> and your program will crash and burn in a horrible flaming mess.
>
>
> [steve at wow-wow ~]$ python -O
> Python 2.5 (r25:51908, Nov  6 2007, 16:54:01)
> [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> assert None is 2
>>>>
>>>>
>
>
> The assert statement is not for runtime error checking. assert is for
> checking your program logic and invariants. If you've ever written a
> comment like:
>
> # When we get here, then x will always be greater than 3.
>
> (or something like that), that's a great candidate for an assertion:
>
> assert x > 3, "x is unexpectedly less than or equal to three"
>
>
> For error checking, you should do something like this:
>
> if not isinstance(key, whatever):
>    raise ValueError
>
> rather than:
>
> try:
>    if not isinstance(key, whatever):
>        raise AssertionError
> except AssertionError:
>    raise ValueError
>
>
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list