Type hinting custom Enum attributes

Viewed 25

I have a custom Enum containing various "exceptions" along with their codes, message etc. which looks like this:

import enum
from typing import NoReturn


class AppException(enum.Enum):

    NotAnInteger = (100, "Value is not an integer", TypeError)
    ValueTooLarge = (101, "Value is too large", ValueError)

    def __new__(cls, code: int, message: str, exception: Exception) -> "AppException":
        member = object.__new__(cls)

        member._value_ = code
        member.code = code
        member.message = message
        member.exception = exception
        return member

    def throw(self, message_override: str = None) -> NoReturn:
        if message_override is not None:
            raise self.exception(message_override)
        else:
            raise self.exception(self.message)

As you can see, each enumeration member has the following attributes: value, code, message and exception. However, Intellisense code-completion in my VS Code does not offer me the attributes code, message and exception and only offers value, see image below:

IMAGE: Attributes code, message and exception are not offered in Intellisense

Is there a way to type hint that the enumeration members have the code, message and exception attributes somehow?

The closest question I found related to this topic is here, but I don't like the solution because if I do this:

...
class AppException(enum.Enum):
    code:int
    message:str
    exception:Exception

    NotAnInteger = (100, "Value is not an integer", TypeError)
    ValueTooLarge = (101, "Value is too large", ValueError)
...

then Intellisense offers me to do the following, which is incorrect and produces errors:

AppException.code

I would prefer something which would rather allow me to use notation like this:

AppException.NotAnInteger.code

Sorry if I used wrong terminology somewhere, I am rather new to Python still. Thanks!

0 Answers
Related