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?
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, 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:
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
.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.