My module raises certain exception when something, not necessarily bad, happens. However, when importing the module I am hoping to do something like this to import them all:
from MyModule import MyModuleExceptions
Currently the way I'm generating the exceptions is via this function:
def gen_exceptions():
EXCEPTION_TYPES = (
"FirstException", # scenario 1
"SecondException", # scenario 2
"UnexpectedException" # Everything else
)
MyModuleExceptionsFactory = namedtuple("exceptions", EXCEPTION_TYPES)
exceptions = {key: type(key, (Exception,), {}) for key in EXCEPTION_TYPES}
return MyModuleExceptionsFactory(**exceptions)
MyModuleExceptions = gen_exceptions()
and in my module I can use it as:
try:
# do stuff
except MyModuleExceptions.FirstException:
# Handle scenario 1
except Exception:
# Everything else
Is the correct way "Pythonic" way of doing it? Or is there a well-established practice that I should follow?