Assertion vs. try-except

Alex Martelli aleaxit at yahoo.com
Fri Oct 20 08:32:39 EDT 2000


"Thomas Weholt" <thomas at cintra.no> wrote in message
news:39f029e8.165482310 at news.eunet.no...
> Hi,
>
> Just wondering what the benefits of assert is, compared to doing a
> try-except for instance. The documentation says :

Strange comparison.  assert, if failing, _raises_ an exception -- so
you may well have assert *inside* a try-except, but I don't see how
you can consider it an *alternative*.

Rather, the alternative may be seen between, say:

    assert foo>bar

and

    if __debug__:
        if not(foo>bar):
            raise AssertionError

which are, indeed, more or less equivalent forms.
As between these, assert is clearly more compact/clear/convenient.

Further, since assert is a statement and therefore known to the
compiler, the compiler knows it can completely omit all of this
code if it's setting __debug__ to 0, i.e., compiling with -O: this
makes code containing assert statement *just as compact and fast
as if it didn't have them at all* when it's compiled with -O.


> "Assert statements are a convenient way to insert debugging assertions
> into a program"
>
> All nice and handy, but is this debugging specific ( should they be
> removed when testing / debugging is over, if that will ever happen ??

They ARE (automatically) removed from generated code when the
Python source is compiled with -O.  They remain in the _source_
code for documentation of key semantics (pre/post/invariants...)
AND ready to re-enable in case of need (e.g. when a previously
closed/released module is opened again for maintenance and/or
enhancement).

> ) ? Why not use a try-except instead and print / handle errors?

You may, if you wish, use a try/except (calling in the try block
code that contains asserts, and catching the AssertionError in
the except clause) -- this may make sense under certain
circumstances; e.g., a long-running server that must NOT go down
although it can dynamically load/reload modules -- just in case
the reloaded module has bugs, catching the AssertionError (or
other exceptions) would tell the server to revert to a safe
previous version of that code.  Pretty far-fetched, but I'm
sure there _are_ real-life situations with such needs...

But in most cases, an AssertionError automatically terminating
things with a traceback, i.e., the default if you _don't_ use
a try/except around it, is quite a reasonable strategy.


Alex






More information about the Python-list mailing list