Search code examples
pythonpython-2.7exceptionpylint

What is the point of calling super in custom error classes in python?


So I have a simple custom error class in Python that I created based on the Python 2.7 documentation:

class InvalidTeamError(Exception):
    def __init__(self, message='This user belongs to a different team'):
        self.message = message

This gives me warning W0231: __init__ method from base class %r is not called in PyLint so I go look it up and am given the very helpful description of "explanation needed." I'd normally just ignore this error but I have noticed that a ton code online includes a call to super in the beginning of the init method of custom error classes so my question is: Does doing this actually serve a purpose or is it just people trying to appease a bogus pylint warning?


Solution

  • This was a valid pylint warning: by not using the superclass __init__ you can miss out on implementation changes in the parent class. And, indeed, you have - because BaseException.message has been deprecated as of Python 2.6.

    Here would be an implementation which will avoid your warning W0231 and will also avoid python's deprecation warning about the message attribute.

    class InvalidTeamError(Exception):
        def __init__(self, message='This user belongs to a different team'):
            super(InvalidTeamError, self).__init__(message)
    

    This is a better way to do it, because the implementation for BaseException.__str__ only considers the 'args' tuple, it doesn't look at message at all. With your old implementation, print InvalidTeamError() would have only printed an empty string, which is probably not what you wanted!