[Python-Dev] Best practices for Enum
Ethan Furman
ethan at stoneleaf.us
Mon May 13 04:25:09 CEST 2013
On 05/12/2013 04:49 PM, Raymond Hettinger wrote:
> After the long design effort for the enum module,
> I'm sure there will be a forthcoming effort to apply
> them pervasively throughout the standard library.
I'd like to apply them where it makes sense. It would be a good way for me to learn all that's in the stdlib while
doing something modestly useful.
> For internal constants such as those in idlelib and regex,
> the user won't see any benefit at all.
Devs are users, too! If it makes our lives easier, then, ultimately, it will make our users lives easier as well.
>But there will be
> a cost in terms of code churn, risk of introducing errors
> in stable code, modestly slowing-down the code, making
> it more difficult to apply bug fixes across multiple versions
> of Python, and increased code verbosity (i.e. changing
> "if direction=LEFT: ..." to "if direction is Direction.LEFT: ...")
There is no need for increased verbosity, as Enums support __eq__ as well:
class Direction(Enum):
LEFT = 1
RIGHT = 2
UP = 3
DOWN = 4
globals.update(Direction.__members__)
direction = ...
if direction == LEFT:
...
> For external constants, some thought needs to be given to:
> * is the current API working just fine (i.e. decimal's ROUND_DOWN)
just fine? or working great?
> * will enums break doctests or any existing user code
doctests rely on repr's, don't they? Then yes. User code? I would think only if the user was relying on a repr or str
of the value. At any rate, that's why this isn't going in until 3.4.
> * will it complicate users converting from Python 2
I would hope it would simplify; I'll backport a 2.x version, though, so anyone interested can play with it.
> * do users now have to learn an additional concept
I don't think enumerations would be a new concept to a computer programmer.
> * does it complicate the module in any way
A little bit of setup at the top, but then it should be easier everywhere else.
> I'm hoping that enums get used only in cases where they
> clearly improve the public API (i.e. cases such as sockets
> that have a large number of integer constants) rather
> than having a frenzy of every constant, everywhere getting
> turned into an enum.
>
> I would like to see enums used as tool for managing complexity,
> rather than becoming a cause of added complexity by being used
> for every problem, the tall and small, even where it is not needed at all.
I will certainly ask for advice on which modules to spend my time on. I know enums are not a cure-all, but they are
great for debugging and interactive work. I don't know about you, but I sure spend a lot of time in those two places.
--
~Ethan~
More information about the Python-Dev
mailing list