3 ms·
Cooke's suggestion is pure special-case magic: class Colour(Enum): red green If Enum is a class, making a subclass should make a subclass like n
by pekk 14y ago
Cooke's suggestion is pure special-case magic:
class Colour(Enum):
red
green
If Enum is a class, making a subclass should make a subclass like normal. Not change how code is parsed within the body of the class definition!
And the same applies to subsequent imaginary suggestions.
If you want a syntax change then introduce a new 'enum' keyword to signal that we are dealing with a new syntax.
Similarly, if you want the statement 'red = 1' to result in Color.red == 'red', that is magic. It doesn't make sense. It should give you 1. The value you just assigned it.
I agree that passing a string to make a class (in the way of namedtuple) is ugly and undesirable and I would never use it.
But I don't think Mr. Cooke has made any suggestion that is better than "design by committee". Code which looks like Python, in a Python file, should behave like Python rather than throwing bizarre curveballs like implicitly turning 1 into "red" or a bitfield.
- suprfsat 14y agoYou can get that syntax by using a metaclass. It's not that hard.
- JeremyBanks 14y agoI 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 14y 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.