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

Ron Adam rrr at ronadam.com
Tue Jan 16 00:27:40 EST 2007


Steven D'Aprano wrote:
> On Mon, 15 Jan 2007 21:01:35 -0600, Ron Adam wrote:
> 
> 
>> 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.
> 
> If you want something more verbose, you have it:
> 
>>>> assert False, "verbose traceback"
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> AssertionError: verbose traceback
> 
> If you want something that won't be turned off by -O, you maybe need to
> write your own:
> 
> def assert_(condition, msg=""):
>     if not condition:
>         raise AssertionError(msg)
> 
>> 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).
> 
> Check out the warnings module.

Yes, I know it's there.  It just seems like assert and warn() overlap currently. 
  Assert doesn't quite fill warn()'s shoes, and warn() isn't as unassertive as 
assert when it's turned off.

A warn statement could be completely ignored and not even cost a function call 
when it's turned off like assert does now.  I don't think it does that 
currently. Isn't there always some overhead when using the warn() function. Or 
is there some magic there?

An if-raise is just as fast as assert when evaluating as True, so there's no 
speed advantage there unless you have a large percentage of raises.  But it does 
looks a lot nicer when you want a short positive test, verses a longer negative 
test with a raise stuck on it.

But I think the developers would not consider this to be a big enough matter to 
be worth changing.  So I'll continue to ignore warn(), and also continue to be 
un-assertive in my python code.

Cheers,
    Ron




More information about the Python-list mailing list