0

Is there a way to have C++ like enumerated types like in Python? For example, in C++ I can do:

enum Foo {
    bar,
    foobar,
    blah
};

and use these as global constants. Is there a similar thing in Python?

Laurel
  • 5,965
  • 14
  • 31
  • 57
Kyle
  • 190
  • 2
  • 9

2 Answers2

1

From the Docs: Enumerations are created using the class syntax, which makes them easy to read and write. An alternative creation method is described in Functional API. To define an enumeration, subclass Enum as follows:

>>>
>>> from enum import Enum
>>> class Color(Enum):
...     red = 1
...     green = 2
...     blue = 3
user3636636
  • 2,409
  • 2
  • 16
  • 31
0

Python3.4+ supports various types of enumerations in the enum module. Obviously it's not quite the same as an enumerated type in C or C++, but it serves the same purpose. If you're stuck in an older version of python, there's a 3rd party backport available on pypi.

Basic usage would look like:

class Foo(enum.Enum):
    bar = 1
    foobar = 2
    blah = 3
mgilson
  • 300,191
  • 65
  • 633
  • 696