[Python-Dev] [Python-checkins] peps: Pre-alpha draft for PEP 435 (enum). The name is not important at the moment, as

Anders J. Munch ajm at flonidan.dk
Wed Feb 27 17:34:35 CET 2013


Hi, offering my DKK 0.50 on the subject.  I've used an in-house enum
type for the better part of a decade - put up at
http://unicollect.dk/download/oss/dc_enum.zip for inspiration.

I'm partial to an int subclass, or at least something very int-like,
because wrapping C libraries is such a major use case. Enums should
support all the operations that C enum's do: indexing, ordering,
bitwise math and unnamed values.

There's a whole bunch of these wrapped C enum's in the standard
library, e.g. in the os, stat and urllib modules.  Wouldn't it be good
to see them converted to enumeration values, to make them sort-of
self-documenting and sort-of typechecked?

- About unnamed values: Suppose for example you gather up some
stat constants in an enum like this: 
class S_I(Enum):
    XOTH = 1
    WOTH = 2
    ROTH = 4
    RWXO = 7
    XGRP = 8
    WGRP = 16
    RGRP = 32
    RWXG = 56
    XUSR = 64
    EXEC = 64
    WRITE = 128
    WUSR = 128
    RUSR = 256
    READ = 256
    RWXU = 448
    SVTX = 512
    SGID = 1024
    SUID = 2048
    FIFO = 4096
    FCHR = 8192
    FDIR = 16384
    FBLK = 24576
    FREG = 32768
    FLNK = 40960
    FSOCK = 49152
Now what happens if you do
>>> S_I(5)
?

This should not raise an exception: 5 is the perfectly valid
combination of XOTH and ROTH.  Supporting unnamed values is also
useful when reading integer values from an external source - file,
network, serial port - where typically you'd first convert the
received value to the enum type before doing any processing.  If
converting to enum type may raise an exception, that would force you
to print raw integer values in diagnostics, where you'd rather have
printed the userfriendly symbolic names.

- The repr of an enum value should be short and sweet.  Because
sometimes you'll be looking at long lists of information with 2-3 of
these on every line, and then <EnumValue: Colors.blue [int=3]> is just
going to be annoyingly verbose.  This is how my library eventually
printed enums:

>>> S_I.ROTH
S_I.ROTH
>>> S_I(4)
S_I.ROTH
>>> S_I(5)
S_I(5)
>>> print(S_I(4))
S_I.ROTH(4)
>>> print(S_I(5))
S_I.?(5)

- A final thing, attempting to compare or convert values from
different enum classes should be a TypeError.  E.g. in wxPython, it's
easy to mistake wx.OK and wx.ID_OK, and a friendly TypeError message
is a good way of detecting this early.

regards, Anders



More information about the Python-Dev mailing list