Reputation: 25557
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?
Upvotes: 2
Views: 914
Reputation: 7682
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)
Upvotes: 2
Reputation:
Instead of using assertions and raising Assertion exception...better perform proper checks using instance() and raise a proper TypeError.
Upvotes: 0
Reputation:
It's not but if your code contains more assert statements than your actual code then I would be angry.
Upvotes: 0
Reputation: 46607
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
.Upvotes: 6