I am new to Python's metaclasses and I am currently trying to achieve the following:
from enum import Enum, EnumMeta
class FlexEnumMeta(EnumMeta):
# see the attempt for the implementation below
...
class FlexEnum(Enum, metaclass=FlexEnumMeta, attrs=('foo', 'bar')):
X = 'abc', 123
Y = 'def', 456
and I would expect it to work as follow:
FlexEnum.X.foo
>>> 'abc'
I read parts of the source code of Enum and aenum to try to understand, and as far as I got was with this code for FlexEnumMeta:
class FlexEnumMeta(EnumMeta):
@classmethod
def __prepare__(metacls, cls, bases, attrs=None, **kwargs):
return {}
def __new__(metacls, name, bases, clsdict, attrs=None, **kwargs):
# Proper way to get an _EnumDict,
# to be passed to super().__new__
enum_dict = super().__prepare__(name, bases, **kwargs)
# Enumeration class members
members = []
for member_name, values in clsdict.items():
# Copy original clsdict in final class members list
if member_name.startswith('_'):
enum_dict[member_name] = values
continue
# Create correspondance between attributes names and values
value_dict = dict(zip(attrs, values))
members.append((member_name, value_dict))
# Copy custom class members in final class members list
for key, value in members:
enum_dict[key] = value
return super().__new__(metacls, name, bases, enum_dict)
class FlexEnum(Enum, metaclass=FlexEnumMeta, attrs=('foo', 'bar')):
X = 'abc', 123
FlexEnum.X
>>> <FlexEnum.X: {'foo': 'abc', 'bar': 123}>
FlexEnum.X.value['foo']
>>> 'abc'
I tried using aenum's MultiValue setting, but I need to have a dict as one of my attributes, and those aren't hashable. And in the end, this is kind of an exercise for me.
fooorbar?