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.



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

Reply via email to