
On 30 January 2013 15:22, Michael Foord <fuzzyman@gmail.com> wrote:
On 30 January 2013 07:26, Antoine Pitrou <solipsis@pitrou.net> wrote:
On Wed, 30 Jan 2013 17:58:37 +1300 Greg Ewing <greg.ewing@canterbury.ac.nz> wrote:
Guido van Rossum wrote:
class color(enum): RED = value() WHITE = value() BLUE = value()
We could do somewhat better than that:
class Color(Enum): RED, WHITE, BLUE = range(3)
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): 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
Michael
However, it's still slightly annoying that you have to specify how many values there are in the range() call. It would be even nicer it we could just use an infinite iterator, such as
class Color(Enum): RED, WHITE, BLUE = values()
Well, how about:
class Color(Enum): values = ('RED', 'WHITE', 'BLUE')
?
(replace values with __values__ if you prefer)
Regards
Antoine.
_______________________________________________ Python-ideas mailing list Python-ideas@python.org http://mail.python.org/mailman/listinfo/python-ideas
--
May you do good and not evil May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give. -- the sqlite blessing http://www.sqlite.org/different.html
-- http://www.voidspace.org.uk/ May you do good and not evil May you find forgiveness for yourself and forgive others May you share freely, never taking more than you give. -- the sqlite blessing http://www.sqlite.org/different.html