assert versus print [was Re: The curious behavior of integer objects]

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Mon Jan 15 21:07:40 EST 2007


On Mon, 15 Jan 2007 17:50:56 -0500, Calvin Spealman wrote:

> assert foo(0x10) == 0  # Assertions are much better tests than prints :-)

I dispute that assertion (pun intended).

Firstly, print statements work even if you pass the -O (optimize) flag
to Python. Your asserts don't.

Secondly, a bare assertion like that gives you very little information: it
just tells you that it failed:

>>> x = 1
>>> assert x == 0
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AssertionError

To provide the same information that print provides, you need something
like this:

assert x == 0, "x == %s not 0" % x

Thirdly, and most importantly, assert and print aren't alternatives,
but complementary tools. Assertions are good for automated testing and
simple data validation, where you already know what values you should
have. Printing is good for interactively exploring your data when you're
uncertain about the values you might get: sometimes it is hard to know
what you should be asserting until you've seen what results your function
returns.



-- 
Steven D'Aprano 




More information about the Python-list mailing list