Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The "correct" way to define an exception in Python without PyLint complaining

I'm trying to define my own (very simple) exception class in Python 2.6, but no matter how I do it I get some warning.

First, the simplest way:

class MyException(Exception):     pass 

This works, but prints out a warning at runtime: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 OK, so that's not the way. I then tried:

class MyException(Exception):     def __init__(self, message):         self.message = message 

This also works, but PyLint reports a warning: W0231: MyException.__init__: __init__ method from base class 'Exception' is not called. So I tried calling it:

class MyException(Exception):     def __init__(self, message):         super(Exception, self).__init__(message)         self.message = message 

This works, too! But now PyLint reports an error: E1003: MyException.__init__: Bad first argument 'Exception' given to super class

How the hell do I do such a simple thing without any warnings?

like image 884
EMP Avatar asked May 24 '10 23:05

EMP


People also ask

How do I fix broad except catching too exception exception?

A good rule of thumb is to limit use of bare 'except' clauses to two cases: If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred. If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise . try...

How do I get exception details in Python?

Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.


1 Answers

When you call super, you need the subclass/derived class as the first argument, not the main/base class.

From the Python online documentation:

class C(B):     def method(self, arg):         super(C, self).method(arg) 

So your exception would be defined as follows:

class MyException(Exception):     def __init__(self, message):         super(MyException, self).__init__(message)         self.message = message 
like image 178
Dustin Avatar answered Oct 04 '22 15:10

Dustin