3 ms·
I don't agree with his suggestion, but it wouldn't require a change to the parser. You can already pull that off using metaclasses. Something like this (unteste
by JeremyBanks 13y ago
I don't agree with his suggestion, but it wouldn't require a change to the parser. You can already pull that off using metaclasses. Something like this (untested):
class EnumBodyDict(dict):
def __init__(self, *a, **kw):
self._keys_accessed = []
dict.__init__(self, *a, **kw)
def __getitem__(self, key):
self._keys_accessed.push(key)
return dict.__getitem__(self, *a, **kw)
class EnumMeta(type):
@classmethod
def __prepare__(metacls, name, bases):
return EnumBodyDict()
def __new__(cls, name, bases, classdict):
next_enum_value = max(classdict.values()) + 1
for name in classdict._keys_accessed:
if name not in classdict:
classdict[name] = next_enum_value
next_enum_value += 1
return type.__new__(cls, name, bases, classdict)
class Enum(object, metaclass=EnumMeta):
# proposed enum implementation here
- eliben 13y agoYou're right, this can be done without changing the Python syntax and in fact there was a proposal (with implementation) on the table for a long time. But eventually it was deemed to be too error prone and the more explicit approach was chosen. Python often resolved a tradeoff in favor of explicitness, and IMHO this ended up being a good decision.