Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I best emulate and/or avoid enum's in Python? [duplicate]

Tags:

python

enums

I've been using a small class to emulate Enums in some Python projects. Is there a better way or does this make the most sense for some situations?

Class code here:

class Enum(object):
'''Simple Enum Class
Example Usage:
>>> codes = Enum('FOO BAR BAZ') # codes.BAZ will be 2 and so on ...'''
def __init__(self, names):
    for number, name in enumerate(names.split()):
        setattr(self, name, number)
like image 701
Lanny Avatar asked Sep 20 '08 15:09

Lanny


2 Answers

Enums have been proposed for inclusion into the language before, but were rejected (see http://www.python.org/dev/peps/pep-0354/), though there are existing packages you could use instead of writing your own implementation:

  • enum: http://pypi.python.org/pypi/enum
  • SymbolType (not quite the same as enums, but still useful): http://pypi.python.org/pypi/SymbolType
  • Or just do a search
like image 86
Ycros Avatar answered Nov 15 '22 04:11

Ycros


The most common enum case is enumerated values that are part of a State or Strategy design pattern. The enums are specific states or specific optional strategies to be used. In this case, they're almost always part and parcel of some class definition

class DoTheNeedful( object ):
    ONE_CHOICE = 1
    ANOTHER_CHOICE = 2 
    YET_ANOTHER = 99
    def __init__( self, aSelection ):
        assert aSelection in ( self.ONE_CHOICE, self.ANOTHER_CHOICE, self.YET_ANOTHER )
        self.selection= aSelection

Then, in a client of this class.

dtn = DoTheNeeful( DoTheNeeful.ONE_CHOICE )
like image 39
S.Lott Avatar answered Nov 15 '22 03:11

S.Lott