[Python-ideas] constant/enum type in stdlib (original) (raw)
Terry Reedy tjreedy at udel.edu
Wed Jan 30 22:32:12 CET 2013
- Previous message: [Python-ideas] constant/enum type in stdlib
- Next message: [Python-ideas] constant/enum type in stdlib
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Previous message: [Python-ideas] constant/enum type in stdlib
- Next message: [Python-ideas] constant/enum type in stdlib
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]