Issue extending Enum and redefining __getitem__

enums, python-3.x

Solution

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.

Problem

I am having some trouble redefining `__getitem__` on a custom subclass of `Enum`. My `__getitem__` is not being called. I guess it has something to do with `Enum`'s metaclass, but I am not sure what and why. Minimal working example (Python 3.4): ``` from enum import Enum, unique @unique class Test(Enum): a = "a" b = "b" def __getitem__(self, name): try: return super().__getitem__(name) except (TypeError, KeyError) as error: print("TEST") if __name__ == "__main__": Test["a"] Test["c"] ``` Result: ``` $ python test.py Traceback (most recent call last): File "test.py", line 18, in <module> Test["c"] File "C:\Development\Python\Python34\lib\enum.py", line 258, in __getitem__ return cls._member_map_[name] KeyError: 'c' ```

Original source

Related problems