Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 312
Rachel Hutchison Avatar asked Aug 09 '16 17:08

Rachel Hutchison


People also ask

Why super () is used in Python?

The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.

Do you need to call Super Python?

All methods that are called with super() need to have a call to their superclass's version of that method. This means that you will need to add super(). __init__() to the .

What does super () __ init __ do?

When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.

What is custom error in Python?

In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class. >>> class CustomError(Exception): ...


1 Answers

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!

like image 127
wim Avatar answered Sep 28 '22 17:09

wim