[Python-ideas] constant/enum type in stdlib
Cameron Simpson
cs at zip.com.au
Wed Jan 30 23:19:26 CET 2013
On 30Jan2013 17:34, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
| Guido van Rossum wrote:
| > this doesn't look so bad, and
| > certainly doesn't violate DRY (though it's somewhat verbose):
| >
| > class color(enum):
| > RED = value()
| > WHITE = value()
| > BLUE = value()
|
| The verbosity is what makes it fail the "truly elegant"
| test for me. And I would say that it does violate DRY
| in the sense that you have to write value() repeatedly
| for no good reason.
|
| Sure, it's not bad enough to make it unusable, but like
| all the other solutions, it leaves me feeling vaguely
| annoyed that there isn't a better way.
How about this:
Color = enum(RED=None, WHITE=None, BLUE=None, yellow=9)
where None means "pick the next natural choice.
The __init__ method goes something like this:
def __init__(self, style=None, **kw):
self._names = {}
self._taken = set()
for name, value in kw.items:
if name in self._names:
raise ValueError("name already taken: " + name)
if value is None:
while seq in self._taken:
seq += 1
value = seq
elif value in self._taken:
raise ValueError("\"%s\": value already taken: %s" % (name, value))
self._names[name] = value
self._taken.add(value)
Obviously this needs a little work:
- you'd allocate the explicit values first and go after the Nones
later so that you don't accidentally take an explicit value
- you'd support (pluggable?) styles, starting with sequential,
allocating 0, 1, 2, ... and bitmask allocating 1, 2, 4, ...
but it lets you enumerate the names without quoting and specify explicit
values and let the class pick default values.
Cheers,
--
Cameron Simpson <cs at zip.com.au>
ERROR 155 - You can't do that. - Data General S200 Fortran error code list
More information about the Python-ideas
mailing list