Clarity vs. code reuse/generality

J. Cliff Dyer jcd at sdf.lonestar.org
Fri Jul 10 12:50:27 EDT 2009


On Fri, 2009-07-10 at 02:57 +0000, Steven D'Aprano wrote:
> On Fri, 10 Jul 2009 03:28:04 +0100, Nobody wrote:
> 
> > On Thu, 09 Jul 2009 04:57:15 -0300, Gabriel Genellina wrote:
> > 
> >> Nobody says you shouldn't check your data. Only that "assert" is not
> >> the right way to do that.
> > 
> > "assert" is not the right way to check your *inputs*. It's a perfectly
> > reasonable way to check data which "should" be valid, as well as a way
> > to document what variables are supposed to contain.
> 
> Where are those variables coming from?
> 
> The distinction really boils down to this:
> 
> * asserts should never fail. If there is any chance that an assertion 
> might fail outside of test suites, then don't use assert.
> 

I'm no expert, but the more I read this thread, and the more I think on
it, the more I believe that asserts don't really need to exist outside
of test suites.  The function that assertions provide is handled in a
far more robust and maintainable way by unit tests and doctests.
Anything else should be handled by more descriptive exceptions.  

The use of assertions in regular code may just be a historical baby step
on the way to real code testing.

To play devils advocate for a moment, one possible use case for assert
statements is if you need to test something that you can't easily get
under a proper unittest or doctest.  Maybe you need to know the value of
a variable halfway through a method.  A judicious assertion can help
supplement your test suite  A better solution would be to refactor so
you can get the needed value under test, but if time constraints won't
allow it, then make your assertion and move on, but only to help you
debug the code, not to protect your code at runtime.  Even then, why not
use a proper Exception (unless speed is a major issue)?

Even if it is only used internally in a module, I would still prefer a
ValueError to an AssertionError.  It tells you what's happening more
clearly.  And it protects you if another caller (even one internal to
the class) calls it with a different set of assumptions.

At minimum, I think there's a heavy burden on an author to justify the
use of AssertionErrors rather than other kinds of Exceptions. 

Cheers,
Cliff




More information about the Python-list mailing list