pythonclasshttpexception

Python, MetaClasses, HTTPException, __init_subclass__ - TypeError: exceptions must derive from BaseException


Could somebody point me to how to solve my problem:

from werkzeug.exceptions import HTTPException

class HTTPExceptions(HTTPException):
    subclasses = dict()

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.subclasses[f'{cls.__name__}'] = cls.__name__


class Error501(HTTPExceptions):
    code = 501

when i try to run:

raise HTTPExceptions.subclasses['Error501']

i got

TypeError: exceptions must derive from BaseException

any chance somebody knows how to solve it?


Solution

  • cls.__name__ is a string, so the way you have defined HTTPExceptions.subclasses is as a map of strings to strings. I assume what you intended is:

    cls.subclasses[f'{cls.__name__}'] = cls
    

    which when run results in

    Traceback (most recent call last):
      File "D:/Dev/python/scratch/subclass_exception.py", line 13, in <module>
        raise HTTPExceptions.subclasses['Error501']
    __main__.Error501