12

Often I will write a generic exception such as the following:

class MyException(Exception):
    "My custom exception."
    pass

This way I can check if that exception is the one I want in something like a try/except block. Yet pylint complains about this as follows:

unnecessary-pass: Unnecessary pass statement

What's the rationale behind this complaint? And is there a more preferred way to do the above? Even the python docs suggest using something like that for a user-defined exception:

class Error(Exception):
    """Base class for exceptions in this module."""
    pass
samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • The CPython interpreter has a optimization command line argument `-OO` that ignores docstrings. – Klaus D. Apr 04 '21 at 02:08
  • @KlausD. Optimization seems not to break the anything in Python 3.7. A class definition with only the docstring and no pass will work just fine with the `-OO` flag. – fabianegli Aug 07 '22 at 12:55

1 Answers1

15

The rationale is that the string literal is a valid Python statement in the class body, therefore the pass is not needed to show indentation.

This is a style issue, so there is no definitive answer for how to fix this. If you feel that the pass is useful, I suggest disabling that warning in pylint.

luther
  • 5,195
  • 1
  • 14
  • 24
  • I see, thanks for pointing that out. In your opinion, how would you handle this? – samuelbrody1249 Apr 04 '21 at 02:13
  • 4
    Personally, since the docstring is an actual statement that has a useful effect, I would consider the `pass` redundant and leave it out. If the only line in the body was a comment, I would include the `pass`, because comments shouldn't make any difference to the code. – luther Apr 04 '21 at 03:35