How to create custom exception from __init__ package?

I have a package __init__.pythat looks something like this:

import sys

__required_python_version = (2,6, 0)

if sys.version_info < __required_python_version:
    this_version = '.'.join([str(x) for x in sys.version_info[0:3]])
    required_version = '.'.join([str(x) for x in __required_python_version])
    raise PythonVersionError(this_version, required_version)

class PythonVersionError(Exception):
    def __init__(self, this_version, required_version):
        self.this_version = this_version
        self.required_version = required_version

    def __str__(self):
        return 'Python version %s is invalid.  Must be at least %s' % (self.this_ver, self.required_ver)

Although I'm sure there is a more elegant way to format these version strings, and I probably could use the standard exception, my real question is: how do I do something like this? Would it be better to move my custom exception to a separate file and import it? Or do I need to transfer the version check to the function that is executed at startup __init__? I'm just looking for recommendations on a preferred approach.

thank

+3
source share
2 answers

, , - , , , .

, . Ay, , , , backtrace. , , - .

, "", , PythonVersin, .

Python PythonVersionError : , if.

, , , PythonVersionError, coorect , /, , , , .

+3

, - .

Exception, ? , , (, , ) PythonVersionError.

? , , RuntimeError.

, , , .

, , PythonVersionException , .

+2

All Articles