Josiah Yoder
Josiah Yoder

Reputation: 3756

What's the appropriate built-in Exception to raise if your library is used with the wrong Python Version?

I have a simple library distributed as a .py file. I would like to raise an exception if the library is called from Python 2 instead of Python 3:

def _check_version():
    if sys.version_info < (3,):
        raise _____Exception('This library depends on Python 3 strings. Please ensure you are using Python 3 instead of Python 2')

What built-in exception should I raise? (How do I fill in the blank above?) The closest exception I can find among the builtin Exceptions is NotImplementedError. The DeprecationWarning feels close, but an exception is more appropriate in this case.

Upvotes: 6

Views: 236

Answers (2)

smci
smci

Reputation: 33938

raise RuntimeError("<pkg> needs Python 3.7 or later")

  • so that the stderr both gives information and can be parsed automatically/ logged
  • and makes it clear that the culprit is <pkg> not some other package or Python itself, which would not be clear to non-Python users; having had to write production scripts that get used by non-Python users. Don't expect non-Python users to read or understand Python tracebacks.

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121894

I'd use RuntimeError for this; there is no more specific exception.

Upvotes: 9

Related Questions