Enums: making a single enum

Marko Rauhamaa marko at pacujo.net
Sat May 26 06:56:50 EDT 2018


Ian Kelly <ian.g.kelly at gmail.com>:
> On Fri, May 25, 2018 at 11:00 PM, Chris Angelico <rosuav at gmail.com> wrote:
>> # Tri-state logic
>> Maybe = object()
>
> The enum has a nice __str__ though.

I use strings for enums:

    class X:
       HERE = "HERE"
       THERE = "THERE"
       EVERYWHERE = "EVERYWHERE"

       def __init__(self):
           self.location = self.HERE

       def move_there(self):
           assert self.location is not self.EVERYWHERE
           self.location = self.THERE


1. Why self.THERE instead of X.THERE?

   X.THERE would work. It would even be preferable if the enums were
   used in a published API. However, in general I don't like to sprinkle
   the name of a class around its implementation.

2. Whe "is not" instead of "!="?

   The enums are defined as strings only as a matter of printing
   convenience. They are treated as arbitrary sentinel objects whose
   only functional property is their identity. Or course, such sentinel
   objects must not be used in contexts where ordinary strings would be
   possible values.


Marko



More information about the Python-list mailing list