Using assert within methods - Python
is it bad practice to use asserts within methods?
e.g.
def add(x, y):
asse开发者_开发技巧rt isinstance(x, int) and isinstance(y, int)
return x + y
Any ideas?
Not at all.
In your sample, provided you have documented that add
expects integers, assert
ing this constraint at the beginning of the method is actually great practice.
Just imagine the other choices you have and how bad they are:
- don't verify your arguments. This means, the method will fail later with a strange backtrace that will presumably confuse the caller and force him to have a look at the implementation of
add
to get a hint what's going on. - be nice and try to convert the input to
int
- very bad idea, users will keep wondering whyadd(2.4,3.1)
keeps returning5
.
It's ok because you may run your application with -O command line option and no code would be generated for your assert statement see here
Update:
But also you should handle all errors anyway. Otherwise after stripping assertions unhandled exceptions may occur. (as McConnell recomended. See his citations here)
It's not but if your code contains more assert statements than your actual code then I would be angry.
Instead of using assertions and raising Assertion exception...better perform proper checks using instance() and raise a proper TypeError.
精彩评论