remove assert statement (Was: Re: PEP new assert idiom)

Robert Brewer fumanchu at amor.org
Sun Nov 7 10:42:21 EST 2004


Gerrit wrote:
> In my opinion, assert is almost useless. It can sometimes be 
> useful for
> debugging purposes, but beyond that, it isn't. The exception raised by
> 'assert' is always AssertionError. That is a major 
> disadvantage, because
> it's not specific. If a method I'm calling would raise an 
> AssertionError
> in some cases, and I want to catch it, I'm catching too much. 
> Creating a
> new exception-class and raising that one is better because of this.
> 
> I don't see the use of a statement like
> "assert isinstance(message, basestring)". It's by far the most common
> use of assert: some assertions about the types of the 
> arguments. This is
> at best redundant. In the case of warnings.py, it's followed by
> re.compile(message, ...). Removing the assertion in this 
> example would result
> in three differences:
>     - The error raised would be TypeError, not 
> AssertionError. Therefore
>       it's more specific and thus easier to catch.
>     - The error would me raised by the re module, not warnings module
>     - The error would be "first argument must be string or compiled
>       pattern" instead of "message must be a string". Therefore, the
>       assertion makes it impossible to pass a compiled pattern instead
>       of a string.
> 
> Duck typing eliminates the use of assert.
> 
> In my opinion, assert should be deprecated and then removed in Py3K:
> assertions are redundant, unspecific, and conflict with the philosophy
> of duck typing and EAFP.
> 
> What do others think of this?

Whole-hearted +1. Let's get it into PEP 3000.

There are cases where isinstance is useful (as you point out, when you
wish to raise a more meaningful error of your own Exception subclass).
But you don't need an assert keyword for that either. ;)


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list