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

Gerrit gerrit at nl.linux.org
Sun Nov 7 08:02:09 EST 2004


Paul Rubin wrote:
> "Raymond Hettinger" <vze4rx4y at verizon.net> writes:
> > Why do you need a statement for this?
> > IMO, a plain function will do the trick:
> 
> I do write such functions sometimes, but using a statement is more
> natural.  That's why the assert statement exists, for example.

I think 'assert' being a statement is on Guido's regrets list. exec and
print are on his regrets list: both should have been a function. I
think the same holds for assert, although I'm not sure.

> statement is very great, and I find myself doing it all the time
> thinking I'll clean it up later.  So I think having a statement for
> runtime checking would be in the correct spirit.

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
is 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?

Gerrit.

-- 
Weather in Twenthe, Netherlands 07/11 13:25:
	12.0°C   wind 3.6 m/s N (57 m above NAP)
-- 
In the councils of government, we must guard against the acquisition of
unwarranted influence, whether sought or unsought, by the
military-industrial complex. The potential for the disastrous rise of
misplaced power exists and will persist.
    -Dwight David Eisenhower, January 17, 1961



More information about the Python-list mailing list