is it bad practice to use asserts within methods?
e.g.
def add(x, y):
assert 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, asserting this constraint at the beginning of the method is actually great practice.
Just imagine the other choices you have and how bad they are:
add to get a hint what's going on.int - very bad idea, users will keep wondering why add(2.4,3.1) keeps returning 5.add clearly state that it only accepts 'int', then it is the responsibility of the caller to keep to this constraint and any contract violation is a programming error.assert in Python raises AssertionError - so it is actually syntatic sugar to raise an exception).AssertError. IMHO, in this case, I'd simply raise TypeError instead.TypeError) that indicates "some data is wrong" instead of "this code is broken" - also, I consider except AssertionError (outside of tests perhaps) rather smelly for that very reason.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)