What's the common practice for enums in Python?


Question

Possible Duplicate:
How can I represent an 'enum' in Python?

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

public enum Materials
{
    Shaded,
    Shiny,
    Transparent,
    Matte
}
1
136
5/23/2017 12:02:46 PM

Accepted Answer

class Materials:
    Shaded, Shiny, Transparent, Matte = range(4)

>>> print Materials.Matte
3
363
3/31/2009 8:39:19 PM

I've seen this pattern several times:

>>> class Enumeration(object):
        def __init__(self, names):  # or *names, with no .split()
            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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon