0

This question is in reference to:

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

In terms of clean code, looks like the ideal way to define an exception would be this:

class MyException(Exception):
    pass

However as stated in the referenced question, this results in a runtime warning:

DeprecationWarning: BaseException.message has been deprecated as of Python 2.6

The accepted answer seems to be to define the message method:

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

Besides being 4 messier lines and less readable lines of code, the biggest issue with this is that you have to redundantly type the name of the new exception (MyException) twice.

I don't use classes in Python very often, so forgive me if I'm way off base here, but might a better way to handle this be to define your own base exception with a non-depreciated .message method since Python seems to have a problem with using the one from BaseException? ::

# Do this only once:
class MyBaseException(Exception):
    def __init__(self, message):
        super(MyBaseException, self).__init__(message)
        self.message = message

# Whenever you want to define a new exception:
class NewException(MyBaseException):
    pass
Community
  • 1
  • 1
Chris Dutrow
  • 48,402
  • 65
  • 188
  • 258
  • 3
    What was the question? I just see a statement. Are you asking is it right? – lukecampbell Oct 21 '12 at 23:12
  • I would go with the simple 2 liner solution... – Karoly Horvath Oct 21 '12 at 23:15
  • 1
    Your problem is not about how to define it (if you don’t override default behaviour, which you don’t, then don’t override `__init__`), but apparently with how you use it, as the warning is thrown when you *access* the property. So fix it there. – poke Oct 21 '12 at 23:28

1 Answers1

1

It seems that somewhere in the code you use MyException.message You may change it to

try: 
   <some code>
except MyException as msg:
    <handle>
volcano
  • 3,578
  • 21
  • 28