Steven D'Aprano wrote:
> On Mon, 21 Dec 2009 21:49:11 +0000, r0g wrote:
> 
>> I use assertions myself e.g.
>>
>>>>> foo = "123456"
>>>>> assert len(foo) <= 5
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>> AssertionError
>>
>>
>> Dunno if this would be considered good or bad programming practice by
>> those more experienced than I (comment always welcome!) but it works for
>> me :)
> 
> 
> Bad practice.
> 
> Assertions are ignored when you run Python with the -O (optimization) 
> command line switch. Your code will behave differently if you use 
> assertions. So you should never use assertions for error-checking, except 
> perhaps for quick-and-dirty throw-away scripts.
> 
> Assertions are useful for testing invariants and "this will never happen" 
> conditions. A trivial example:
> 
> result = math.sin(2*math.pi*x)
> assert -1 <= result <= 1
> 
> Assertions are also useful in testing, although be careful: since the 
> assert statement is ignored when running with -O, that means you can't 
> test your application when running with -O either! But do not use them 
> for data validation unless you're happy to run your application with no 
> validation at all.
> 
> 
> 


Yikes, glad to be set me straight on that one! Thanks :) It's a pity
though, I really like the way it reads. Is there anything similar with
ISN'T disabled when optimizations are turned on?

I guess I could do the following but it seems a bit ugly in comparison :(

if len(foo) <= 5: raise Exception



Roger.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to