[Tutor] eval func with floating...

Steven D'Aprano steve at pearwood.info
Wed Aug 24 03:52:11 CEST 2011


Christopher King wrote:
>> If the user ever sees an AssertionError, your code is buggy.
>>
> Well you saw that I caught the AssertionError, so the user
> wouldn't technically see it. For the other stuff, I didn't know
> the etiquette for assertion

It's not etiquette, it is the actual way assert works.


If you have code that looks like this:

assert x > 0
print x + 1


and the user runs your code using "python -O", the code is converted to:

print x + 1

and the assert is just *gone*.

It is as simple as that. Any time you use an assert, you should imagine 
that it will just *disappear* some times.

When are assertions useful? If you have ever written code like this:


if x > 0:
     print x + 1
else:
     # This can never happen!
     raise RuntimeError('unexpected internal error')


that's a good case for using an assert. Because you are sure that the 
else can never happen, it won't matter if the assert goes away. But 
because you can't be absolutely 100% sure, it's better to code 
defensively with a check that your program logic is correct.




-- 
Steven


More information about the Tutor mailing list