Paul Manta
Paul Manta

Reputation: 31567

Pythonic handling of this error case

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__

Upvotes: 2

Views: 136

Answers (2)

Eli Bendersky
Eli Bendersky

Reputation: 273366

It appears to me that the assert here 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 assert here 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 an assert in 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 assert here to validate something the user could err with, then it's not a good idea.

Upvotes: 1

user395760
user395760

Reputation:

assert is not for input validation, it's for finding flaws in the assumptions you built your code on. It's a debugging and documentation tool, but it can be disabled. If you want to provide a good error message, raise TypeError("Object is not a bound method") - that's what it's for.

Upvotes: 4

Related Questions