[Python-ideas] constant/enum type in stdlib
Terry Reedy
tjreedy at udel.edu
Wed Jan 30 22:32:12 CET 2013
On 1/30/2013 10:30 AM, Michael Foord wrote:
> On 30 January 2013 15:22, Michael Foord
> With a Python 3 metaclass that provides default values for *looked
> up* entries you could have this:
>
> class Color(Enum):
> RED, WHITE, BLUE
>
> The lookup would create the member - with the appropriate value.
>
> class values(dict):
> def __init__(self):
> self.value = 0
> def __getitem__(self, key):
Adding 'print(self.value, key)' here prints
0 __name__
0 __name__
1 RED
2 WHITE
3 BLUE
(I do not understand why it is the second and not first lookup of
__name__ that increments the counter, but...)
> try:
> return dict.__getitem__(self, key)
> except KeyError:
> value = self[key] = self.value
> self.value += 1
> return value
>
> class EnumMeta(type):
>
> @classmethod
> def __prepare__(metacls, name, bases):
> return values()
>
> def __new__(cls, name, bases, classdict):
> result = type.__new__(cls, name, bases, dict(classdict))
> return result
>
>
> class Enum(metaclass=EnumMeta):
> pass
> class Color(Enum):
> RED, WHITE, BLUE
So RED, WHITE, BLUE are 1, 2, 3; not 0, 1, 2 as I and many readers might
expect. That aside (which can be fixed), this is very nice.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list