In the code below, is my use of assert justified? If anything is wrong, an error will occur anyway when I try to access the attributes. On the other hand, the assert provides a descriptive error message.
Do you think I should keep the assertion?
class WeakBoundMethod:
def __init__(self, meth):
assert (hasattr(meth, '__func__') and hasattr(meth, '__self__')),\
'Object is not a bound method.'
self._self = weakref.ref(meth.__self__)
self._func = meth.__func__
It appears to me that the
asserthere is checking an assumption the code is making. It will fail if the class is used incorrectly (i.e. programming error).If this is indeed the case, then the use of
asserthere is IMHO justified. True, Python generously throws exceptions when things are used incorrectly, and EAFP is a good strategy. Yet, sometimes the errors thrown by the interpreter aren’t descriptive enough to make it easy to locate the problem, and anassertin such cases is appropriate. It should also be coupled with appropriate documentation that states how the class expects to be used (i.e. the passed method should have certain attributes).If I have misunderstood your sample and you’re using the
asserthere to validate something the user could err with, then it’s not a good idea.