I love assert

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Nov 14 06:15:37 EST 2014


Peter Cacioppi wrote:

> I get the impression that most Pythonistas aren't as habituated with
> assert statements as I am. Is that just a misimpression on my part? If
> not, is there a good reason to assert less with Python than other
> languages?

I love assert, and use it frequently. But there are good reasons and bad
reasons to use it. I've written an essay about the good reasons to use
assert, e.g. defensive programming, program invariants, checked comments,
design by contract, and when not to use them, e.g. testing arguments to
public interfaces.

http://import-that.dreamwidth.org/676.html


> As far as I can tell, Python supports assert perfectly well. When run with
> the optimization flagging, the asserts are truly removed.
> 
> I think one needs to take care with some basic assert coding - it's not a
> substitute for unit tests, it doesn't absolve you of normal exception
> responsibilities, and, most of all, it should be used for passive
> inspection and not action. But given these guidelines, I still find it
> very useful as "active comments".

Agreed completely!



-- 
Steven




More information about the Python-list mailing list