Issue extending Enum and redefining __getitem__

Your overriding of __getitem__ would be invoked if you use square-brackets on an instance of an Enum.

Accessing it like Test["A"] would invoke the __getitem__ method of the meta-class. So in your case, you'd need to subclass the EnumMeta meta-class, overriding its __getitem__, then create your own enum class with that meta class.

You can take a look at the source code here.


As @shx2 pointed out, you're not invoking the __getitem__() of yourEnum subclass. Here's how to fix that by also subclassing Enum's metaclass:

from enum import Enum, EnumMeta, unique

class TestEnumMeta(EnumMeta):
    def __getitem__(self, name):
        try:
            return super().__getitem__(name)
        except (TypeError, KeyError) as error:
            print("TEST")

@unique
class Test(Enum, metaclass=TestEnumMeta):
    a = "a"
    b = "b"

if __name__ == "__main__":
    Test["a"]
    Test["c"]  # -> TEST