Calvin Spealman wrote: > On 1/15/07, Steven D'Aprano <[EMAIL PROTECTED]> wrote: >> 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). > > Hah! > >> Firstly, print statements work even if you pass the -O (optimize) flag >> to Python. Your asserts don't. > > This is true, but the concept can be adapted to a things like an > assert_() function. > >> 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 > > What information would I need to know if my test passed? Nothing, I > say. I only want to know when the tests fail, especially as I add more > of them. Having no output is a great way to know nothing puked. > >> 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. > > True, but I intended my statement as a nudge towards more proper > testing. Even when testing things out, I often use an assert rather > than a print, to verify some condition.
There have been times where I would like assert to be a little more assertive than it is. :-) ie.. not being able to turn them off with the -0/-00 switches, and having them generate a more verbose traceback. Maybe have an alternative 'warn' as an alternative debugging version that could be set to ignore, soft (print to log), and hard (raise an error). An assert statement is a little clearer than an if...raise... in cases where you want to raise a value exception of some type. But I'm probably in the minority on this one. Ron -- http://mail.python.org/mailman/listinfo/python-list