tags:

views:

700

answers:

4

What's the common practice for enums in Python? I.e. how are they replicated in Python?

public enum Materials
{
    Shaded,
    Shiny,
    Transparent,
    Matte
}
+5  A: 

I've seen this pattern several times:

>>> class Enumeration(object):
        def __init__(self, names):
            for number, name in enumerate(names.split()):
                setattr(self, name, number)

>>> foo = Enumeration("bar", "baz", "quux")
>>> foo.quux
2

You can also just use class members, though you'll have to supply your own numbering:

>>> class Foo(object):
        bar  = 0
        baz  = 1
        quux = 2

>>> Foo.quux
2

If you're looking for something more robust (sparse values, enum-specific exception, etc.), try this recipe.

Ben Blank
A: 

I have no idea why Enums are not support natively by Python. The best way I've found to emulate them is by overridding _ str _ and _ eq _ so you can compare them and when you use print() you get the string instead of the numerical value.

class enumSeason():
    Spring = 0
    Summer = 1
    Fall = 2
    Winter = 3
    def __init__(self, Type):
        self.value = Type
    def __str__(self):
        if self.value == enumSeason.Spring:
            return 'Spring'
        if self.value == enumSeason.Summer:
            return 'Summer'
        if self.value == enumSeason.Fall:
            return 'Fall'
        if self.value == enumSeason.Winter:
            return 'Winter'
    def __eq__(self,y):
       return self.value==y.value

Usage:

>>> s = enumSeason(enumSeason.Spring)

>>> print(s)

Spring
Spell
PEP354 has a rejection notice. See http://www.python.org/dev/peps/pep-0354/#rejection-notice
Fred Larson
+13  A: 
class Materials:
    Shaded, Shiny, Transparent, Matte = range(4)

>>> print Materials.Matte
3
Van Gale
I haven't seen that one before, good stuff.
Ben Blank
Good tip, thanks.
Joan Venge
The only problem is I need the first item to be 1. Is that possible to do with your method?
Joan Venge
Of all the methods i've seen, this is probably my favorite. Very elegant!
goldenratio
This is the one :) Good to see others use it.
jkp
A: 

You could probably use an inheritance structure although the more I played with this the dirtier I felt.

class AnimalEnum:
  @classmethod
  def verify(cls, other):
    return issubclass(other.__class__, cls)


class Dog(AnimalEnum):
  pass

def do_something(thing_that_should_be_an_enum):
  if not AnimalEnum.verify(thing_that_should_be_an_enum):
    raise OhGodWhy
Trey Stout