I love assert

Ben Finney ben+python at benfinney.id.au
Tue Nov 11 21:03:58 CET 2014


Peter Cacioppi <peter.cacioppi at gmail.com> writes:

> 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 don't know about comparisons like “use less with Python than other
languages”. But I can explain why I don't use ‘assert’ much.

> As far as I can tell, Python supports assert perfectly well. When run
> with the optimization flagging, the asserts are truly removed.

Exactly. I prefer the code I write to have as few surprises as possible.
A reader familiar with Python should be able to read it and know what it
does; ideally, even if that reader doesn't recall every detail of how
Python operates.

An ‘assert’ statement in the code will sometimes be active, and
sometimes be a no-op, for *exactly* the same code under different
circumstances. That's a trap for the reader, and I'd rather not set it.

> 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".

It's fine for debugging code while developing. But, in my opinion, it
should never stay there, and should be removed before committing to VCS.

-- 
 \         “True greatness is measured by how much freedom you give to |
  `\      others, not by how much you can coerce others to do what you |
_o__)                                               want.” —Larry Wall |
Ben Finney




More information about the Python-list mailing list