By sectrean

2008-08-31 15:55:47 8 Comments

I'm mainly a C# developer, but I'm currently working on a project in Python.

How can I represent the equivalent of an Enum in Python?


@Riaz Rizvi 2013-05-10 16:22:42

The new standard in Python is PEP 435, so an Enum class will be available in future versions of Python:

>>> from enum import Enum

However to begin using it now you can install the original library that motivated the PEP:

$ pip install flufl.enum

Then you can use it as per its online guide:

>>> from flufl.enum import Enum
>>> class Colors(Enum):
...     red = 1
...     green = 2
...     blue = 3
>>> for color in Colors: print color

@Alexandru Nedelcu 2008-08-31 16:06:14

Before PEP 435, Python didn't have an equivalent but you could implement your own.

Myself, I like keeping it simple (I've seen some horribly complex examples on the net), something like this ...

class Animal:
    DOG = 1
    CAT = 2

x = Animal.DOG

In Python 3.4 (PEP 435), you can make Enum the base class. This gets you a little bit of extra functionality, described in the PEP. For example, enum members are distinct from integers, and they are composed of a name and a value.

class Animal(Enum):
    DOG = 1
    CAT = 2

# <Animal.DOG: 1>

# 1

# "DOG"

If you don't want to type the values, use the following shortcut:

class Animal(Enum):
    DOG, CAT = range(2)

Enum implementations can be converted to lists and are iterable. The order of its members is the declaration order and has nothing to do with their values. For example:

class Animal(Enum):
    DOG = 1
    CAT = 2
    COW = 0

# [<Animal.DOG: 1>, <Animal.CAT: 2>, <Animal.COW: 0>]

[animal.value for animal in Animal]
# [1, 2, 0]

Animal.CAT in Animal
# True

@bortzmeyer 2008-09-26 19:16:16

What's the point of defining numerical values (1 and 2)? They seem useless, and that's why I prefer zacherates' solution.

@strager 2009-02-03 00:54:28

It is clear from the example that constants are being defined. There is an issue with type safety, however, which may cause problems.

@aatifh 2009-03-05 15:38:08

You should have first created an instance of Animal class.. X = Animal() z = X.DOG

@Georg Schölly 2009-03-05 15:41:07

No, it's a class variable.

@Alexandru Nedelcu 2009-07-21 08:21:36

Python is dynamic by default. There's no valid reason to enforce compile-time safety in a language like Python, especially when there is none. And another thing ... a good pattern is only good in the context in which it was created. A good pattern can also be superseded or completely useless, depending on the tools you're using.

@Casebash 2009-10-25 04:48:29

Using range is generally better

@shahjapan 2010-02-06 03:15:15

what if we inherit set and use getattr method to use Enum, see…

@L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳ 2010-05-07 00:47:03

What if I have 100 values, I have to write the numbers for each of them? Yuk!

@Alexandru Nedelcu 2010-05-07 12:04:42

@Longpoke if you have 100 values, then you're definitely doing something wrong ;) I like numbers associated with my enums ... they are easy to write (vs strings), can be easily persisted in a database, and are compatible with the C/C++ enum, which makes for easier marshaling.

@Tobu 2010-07-20 07:53:05

I use this, with the numbers replaced by object().

@Beni Cherniavsky-Paskin 2012-06-20 11:19:55

X = object() is inconvenient because it doesn't know what it is (you can only compare to namespace.X), and risky because copy.deepcopy() or serialization/deserialiaztion creates a new one, which isn't equal to any of those you defined! Numbers are at least safe, but strings are usually better.

@kdazzle 2012-06-24 07:49:51

Would this be better implemented with a dictionary, so that it would be easier to match the animal type with its ordinal value?

@Peter Hansen 2013-05-10 19:05:59

The original PEP354 is no longer merely rejected, but is now marked superseded. PEP435 adds a standard Enum for Python 3.4. See

@Voo 2013-08-12 22:44:55

This answer should also mention the flufl.enum package and enables backcomp for python<3.4.

@shrewmouse 2017-06-07 15:35:40

@AlexandruNedelcu, Everyone that has come to this page looking for an answer to this question probably has a good reason to enforce valid values with an enum. How about enforcing an API, improving readability, improving an IDE interface, or limiting the effects when the values of constants change between revisions?

@Tyson 2018-03-01 08:27:24

I use this style of enumeration because: a) removing an item doesn't renumber following items (important if values are saved to disk); b) static type checkers (eg: mypy) will know that Animal.CAT is an int and show type errors if used incorrectly; c) ancillary data can be stored alongside the values (eg: MAMMALS = {CAT, DOG} as another class attribute).

@Mark Harrison 2008-08-31 20:31:22

If you need the numeric values, here's the quickest way:

dog, cat, rabbit = range(3)

In Python 3.x you can also add a starred placeholder at the end, which will soak up all the remaining values of the range in case you don't mind wasting memory and cannot count:

dog, cat, rabbit, horse, *_ = range(100)

@M.J 2019-02-28 04:42:34

But this might take more memory!

@Gabriel Devillers 2019-09-16 13:48:22

I do not see the point of the starred placeholder given that Python will check the number of values to unpack (so it will do the counting for you).

@Mark Harrison 2019-09-16 21:18:06

@GabrielDevillers, I think Python will raise an exception if there is a mismatch on number of elements in the tuple to assign.

@Gabriel Devillers 2019-09-16 22:29:30

Indeed, it does in my test (Python2,3) but that means that any counting mistake from the programmer will be catched on first test (with a message giving the correct count).

@Mark Harrison 2019-09-17 00:47:56

@GabrielDevillers, ah, understand now... good point!

@javadba 2019-10-31 22:33:49

I can't count. Can the starred placeholder also fix my finances?

@Alec Thomas 2009-11-08 03:15:28

Enums have been added to Python 3.4 as described in PEP 435. It has also been backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 on pypi.

For more advanced Enum techniques try the aenum library (2.7, 3.3+, same author as enum34. Code is not perfectly compatible between py2 and py3, e.g. you'll need __order__ in python 2).

  • To use enum34, do $ pip install enum34
  • To use aenum, do $ pip install aenum

Installing enum (no numbers) will install a completely different and incompatible version.

from enum import Enum     # for enum34, or the stdlib version
# from aenum import Enum  # for the aenum version
Animal = Enum('Animal', 'ant bee cat dog')

Animal.ant  # returns <Animal.ant: 1>
Animal['ant']  # returns <Animal.ant: 1> (string lookup)  # returns 'ant' (inverse lookup)

or equivalently:

class Animal(Enum):
    ant = 1
    bee = 2
    cat = 3
    dog = 4

In earlier versions, one way of accomplishing enums is:

def enum(**enums):
    return type('Enum', (), enums)

which is used like so:

>>> Numbers = enum(ONE=1, TWO=2, THREE='three')
>>> Numbers.ONE
>>> Numbers.TWO
>>> Numbers.THREE

You can also easily support automatic enumeration with something like this:

def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    return type('Enum', (), enums)

and used like so:

>>> Numbers = enum('ZERO', 'ONE', 'TWO')
>>> Numbers.ZERO
>>> Numbers.ONE

Support for converting the values back to names can be added this way:

def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    reverse = dict((value, key) for key, value in enums.iteritems())
    enums['reverse_mapping'] = reverse
    return type('Enum', (), enums)

This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw KeyError if the reverse mapping doesn't exist. With the first example:

>>> Numbers.reverse_mapping['three']

@Pascal Bourque 2012-01-25 14:46:15

Ingenious solution! I wonder if/how it could be made to print the name of the identifiers when debugging? For example, having print "The value is %r" % Numbers.ONE output The value is ONE instead of The value is 1...

@Marcin 2012-02-29 15:10:15

Note that this isn't really that similar to a C enum, in that one cannot meaningfully have variables/objects of a type returned by enum.

@Oxdeadbeef 2012-06-21 22:46:38

neat solution. @Pascal Bourque, this is not exactly what you want, but may give you some idea:

@Jake Biesinger 2012-07-17 14:47:40

Although the values themselves aren't typed, you can type the enumeration class so they're distinct from each other: return type(named.get('enum_type', 'Enum'), (), enums) then calling with enum('ONE', 'TWO', THREE='three', enum_type='Numbers')

@DRayX 2012-08-15 17:43:42

This is very similar to my enum snippet: def enum(*args): return type('Enum', (object,), dict(zip(args, iter(object, None)))).

@acjay 2012-10-22 12:52:56

@PascalBourque: Just added a reverse mapping to address your question. See the bottom

@Tom Swirly 2013-04-09 00:51:41

Oh, I noticed a slight improvement that could be made. zip(x, range(len(x)) is a code smell - it can be replaced by enumerate to get enums = dict((x, i) for i, x in enumerate(sequential)), **named) which doesn't construct all those lists that zip/range do.

@Sled 2013-04-24 21:23:09

@Alec Thomas I think the reverse_mapping is broken since Numbers.THREE == Numbers.reverse_mapping['three'] is false. Is there a simple fix for this?

@Alec Thomas 2013-04-25 20:55:38

@ArtB That is by design: Numbers.THREE == 'three' and Numbers.reverse_mapping['three'] == 'THREE'.

@Sled 2013-04-25 21:05:26

Sorry, I was expecting Java's Enum.valueOf semantics where the reverse gives you the enum.

@Nikolai Golub 2013-04-29 10:53:20

Is that slower than the named tuple?

@Thijs van Dien 2013-05-18 09:56:45

It may be of value to compare your solutions with PEP 435.

@quirkystack 2013-09-22 19:46:57

I am a newbie to Python. I have used the above version in my code which is on Python2.7 and it works fine.. Now I want to iterate over the above enumeration (python2.7) version but can't seem to do it..I presume it has to implement something like iterable like in Java.. any ideas please?

@tobych 2013-10-01 17:23:31

For Python 2.7 I prefer the simpler answer below, because my IDE (PyCharm) can auto-complete members.

@ToolmakerSteve 2013-12-10 22:31:20

Very useful, but one caveat compared to C enums: In the solution (for older pythons) the names are not constants: Numbers.ONE = 2 could be typed later, altering the value. See @hans_meine 's named_constants for a safer solution:

@ToolmakerSteve 2013-12-11 01:15:52

Here, building on others' work, I now have developed a simple solution to enum-like type.attribute named constants; unlike the above answer, the values are constants (read-only). Thanks for the inspiration to find an even better way!

@sastanin 2014-03-06 15:39:37

The problem with enum package is that its enum types don't survive pickling-unpickling. Create an enumaration Foo = Enum("foo", "bar"), then compare pickle.loads(pickle.dumps( ==; the result is False. It hurts when you have a multiprocessing program, because seemingly equal values stop passing equality check.

@abarnert 2014-09-29 08:58:18

@sastanin: That's not a problem with the stdlib enum, or the enum34 backport. Foo = Enum("Foo", "foo bar"), then pickle.loads(pickle.dumps( == is True. And if you manage to confuse it somehow (e.g., Bar = Enum("Foo", "foo bar")), you get a PicklingError instead of silent failure.

@dylnmc 2014-10-28 14:34:08

@quirkystack (question about iterating over enum) try using iter; if, for example, you have a class that "extends" enum called test_enum, you can do for i in iter(test_enum): print, i.value. You can even do for i in list(test_enum): print, i.value. ==Test== >>> from enum import Enum ||>>> class t(Enum): a="a";b="bee";c=3 ||... ||>>> for i in iter(t): print, i.value ||... ||c 3 ||a a ||b bee (|| = newline because there are no newlines in comments :[ )

@Jesse W at Z 2014-11-14 19:29:50

Regarding the relative performance of (mentioned by Tom Swirly above): in IPython 2.2.0 (running Python 2.7.5) I get the following: In [18]: %timeit dict(zip(order,range(len(order)))) 1000000 loops, best of 3: 1.5 µs per loop In [19]: %timeit {x[1]:x[0] for x in enumerate(order)} 1000000 loops, best of 3: 896 ns per loop %timeit {v:i for i,v in enumerate(order)} 1000000 loops, best of 3: 684 ns per loop

@user541905 2015-04-29 10:56:40

Running the first version in Python 2.7 gives me TypeError: issubclass() arg 1 must be a class

@L S 2015-04-30 20:02:21

When I use this with Python 2.7, the result for type(Numbers) is <type 'type'>. I expected it to be <type 'Enum'>. Why doesn't it return that?

@gaborous 2015-05-31 12:41:22

Also you can use __slots__ to optimize for Python < 3.4 (example case here)

@CodingLab 2016-03-20 04:58:40

@dylnmc somehow your iter() solution did not work for me(python 2.7). for x in State.reverse_mapping.keys(): print x buf this code works

@Zoey Hewll 2016-08-31 02:31:02

This method wouldn't work if you tried something like dict('A','B','C'=0), as the values of C and A would no longer be distinct.

@seenu s 2017-03-10 05:52:09

I was not been able to understand, why did they pass kwargs(**named) in the method enum(*sequential, **named) ? Please explains. Without kwargs also it will works. I checked it.

@bscan 2017-03-10 15:52:56

It would be nice to update the Python 2 function to be compatible with Python 3's functional API of Enum(name, values)

@M.J 2019-02-28 04:39:21

Does 'type()' do this function!

@Saša Šijak 2013-12-11 13:49:01

From Python 3.4 there will be official support for enums. You can find documentation and examples here on Python 3.4 documentation page.

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

@srock 2014-06-10 19:10:36

Back porting is now supported as well. This is the way to go.

@shahjapan 2010-02-02 07:21:46

Here is one implementation:

class Enum(set):
    def __getattr__(self, name):
        if name in self:
            return name
        raise AttributeError

Here is its usage:

Animals = Enum(["DOG", "CAT", "HORSE"])


@Joonas Pulakka 2011-01-11 14:12:41

Excellent. This can be further improved by overriding __setattr__(self, name, value) and maybe __delattr__(self, name) so that if you accidentally write Animals.DOG = CAT, it won't silently succeed.

@Eric O Lebigot 2011-10-25 12:48:51

@shahjapan: Interesting, but relatively slow: a test is done for each access like Animals.DOG; also, the values of the constats are strings, so that comparisons with these constants are slower than if, say, integers were allowed as values.

@Eric O Lebigot 2011-10-31 09:39:37

@shahjapan: I would argue that this solution is not as legible as the shorter solutions of Alexandru or Mark, for instance. It's an interesting solution, though. :)

@Harshith J.V. 2012-11-15 05:43:14

I tried using setattr() function inside __init__() method instead of overidding __getattr__() method. I am assume this is supposed work the same way: class Enum(object): def __init__(self, enum_string_list): if type(enum_string_list) == list: for enum_string in enum_string_list: setattr(self, enum_string, enum_string) else: raise AttributeError

@user2233706 2014-04-21 04:49:05

I had upvoted this post and copied and pasted the code without testing it. Now I see that the enum value is not an integer, but a string. Animals.DOG prints "DOG", not 0.

@bgusach 2015-01-30 11:57:16

@AndréTerra: how do you check for set membership in a try-except block?

@Clément 2016-11-25 20:52:30

@AndreTerra: Uh? What would you put in your try-catch?

@shao.lo 2017-07-23 19:07:10

This technique works great for string constants. You can do "My pet is a "+Animals.DOG. The python3 Enum class would require a str method to remove the class name and would still require a str() cast...unless I'm missing something.

@danger89 2014-03-28 21:44:30

Keep it simple:

class Enum(object): 
    def __init__(self, tupleList):
            self.tupleList = tupleList

    def __getattr__(self, name):
            return self.tupleList.index(name)



@estani 2014-11-11 09:26:34

def enum(*sequential, **named):
    enums = dict(zip(sequential, [object() for _ in range(len(sequential))]), **named)
    return type('Enum', (), enums)

If you name it, is your problem, but if not creating objects instead of values allows you to do this:

>>> DOG = enum('BARK', 'WALK', 'SIT')
>>> CAT = enum('MEOW', 'WALK', 'SIT')

When using other implementations sited here (also when using named instances in my example) you must be sure you never try to compare objects from different enums. For here's a possible pitfall:

>>> DOG = enum('BARK'=1, 'WALK'=2, 'SIT'=3)
>>> CAT = enum('WALK'=1, 'SIT'=2)
>>> pet1_state = DOG.BARK
>>> pet2_state = CAT.WALK
>>> pet1_state == pet2_state


@royal 2010-11-03 23:02:54

So, I agree. Let's not enforce type safety in Python, but I would like to protect myself from silly mistakes. So what do we think about this?

class Animal(object):
    values = ['Horse','Dog','Cat']

    class __metaclass__(type):
        def __getattr__(self, name):
            return self.values.index(name)

It keeps me from value-collision in defining my enums.

>>> Animal.Cat

There's another handy advantage: really fast reverse lookups:

def name_of(self, i):
    return self.values[i]

@trojjer 2013-11-28 16:23:07

I like this, but you might as well lock values in for efficiency with a tuple? I played around with it and came up with a version that sets self.values from args in init. It is nice to be able to declare Animal = Enum('horse', 'dog', 'cat'). I also catch the ValueError in getattr in the event of a missing item in self.values -- it seems better to raise an AttributeError with the supplied name string instead. I couldn't get the metaclass to work in Python 2.7 based on my limited knowledge in that area, but my custom Enum class works fine with straight instance methods.

@Ashwin Nanjappa 2009-10-07 02:47:33

The best solution for you would depend on what you require from your fake enum.

Simple enum:

If you need the enum as only a list of names identifying different items, the solution by Mark Harrison (above) is great:

Pen, Pencil, Eraser = range(0, 3)

Using a range also allows you to set any starting value:

Pen, Pencil, Eraser = range(9, 12)

In addition to the above, if you also require that the items belong to a container of some sort, then embed them in a class:

class Stationery:
    Pen, Pencil, Eraser = range(0, 3)

To use the enum item, you would now need to use the container name and the item name:

stype = Stationery.Pen

Complex enum:

For long lists of enum or more complicated uses of enum, these solutions will not suffice. You could look to the recipe by Will Ware for Simulating Enumerations in Python published in the Python Cookbook. An online version of that is available here.

More info:

PEP 354: Enumerations in Python has the interesting details of a proposal for enum in Python and why it was rejected.

@ToonAlfrink 2014-06-13 16:09:23

with range you can omit the first argument if it's 0

@Ana Nimbus 2018-06-02 03:51:03

Another fake enum that suits some purposes is my_enum = dict(map(reversed, enumerate(str.split('Item0 Item1 Item2')))). Then my_enum can be used in look-up, e.g., my_enum['Item0'] can be an index into a sequence. You might want to wrap the result of str.split in a function that throws an exception if there are any duplicates.

@majkelx 2019-09-30 12:00:35

Nice! For Flags you can Flag1, Flag2, Flag3 = [2**i for i in range(3)]

@Rafay 2014-03-17 17:34:55

Here is a nice Python recipe that I found here:

def enum(typename, field_names):
    "Create a new enumeration type"

    if isinstance(field_names, str):
        field_names = field_names.replace(',', ' ').split()
    d = dict((reversed(nv) for nv in enumerate(field_names)), __slots__ = ())
    return type(typename, (object,), d)()

Example Usage:


More details can be found on the recipe page.

@David 2013-09-05 04:12:03

Didn't see this one in the list of answers, here is the one I whipped up. It allows the use of 'in' keyword and len() method:

class EnumTypeError(TypeError):

class Enum(object):
    Minics enum type from different languages
    Letters = Enum(list('abc'))
    a = Letters.a
    print(a in Letters) # True
    print(54 in Letters) # False
    def __init__(self, enums):
        if isinstance(enums, dict):
        elif isinstance(enums, list) or isinstance(enums, tuple):
            self.__dict__.update(**dict((v,k) for k,v in enumerate(enums)))
            raise EnumTypeError

    def __contains__(self, key):
        return key in self.__dict__.values()

    def __len__(self):
        return len(self.__dict__.values())

if __name__ == '__main__':
    print('Using a dictionary to create Enum:')
    Letters = Enum(dict((v,k) for k,v in enumerate(list('abcde'))))
    a = Letters.a
    print('\tIs a in e?', a in Letters)
    print('\tIs 54 in e?', 54 in Letters)
    print('\tLength of Letters enum:', len(Letters))

    print('\nUsing a list to create Enum:')
    Letters = Enum(list('abcde'))
    a = Letters.a
    print('\tIs a in e?', a in Letters)
    print('\tIs 54 in e?', 54 in Letters)
    print('\tLength of Letters enum:', len(Letters))

        # make sure we raise an exception if we pass an invalid arg
        Failure = Enum('This is a Failure')
    except EnumTypeError:


Using a dictionary to create Enum:
        Is a in e? True
        Is 54 in e? False
        Length of Letters enum: 5

Using a list to create Enum:
        Is a in e? True
        Is 54 in e? False
        Length of Letters enum: 5

@Chris Johnson 2013-06-19 21:30:47

Here's an approach with some different characteristics I find valuable:

  • allows > and < comparison based on order in enum, not lexical order
  • can address item by name, property or index: x.a, x['a'] or x[0]
  • supports slicing operations like [:] or [-1]

and most importantly prevents comparisons between enums of different types!

Based closely on

Many doctests included here to illustrate what's different about this approach.

def enum(*names):
    Well-behaved enumerated type, easier than creating custom classes

    Create a custom type that implements an enumeration.  Similar in concept
    to a C enum but with some additional capabilities and protections.  See

    names       Ordered list of names.  The order in which names are given
                will be the sort order in the enum type.  Duplicate names
                are not allowed.  Unicode names are mapped to ASCII.

    Object of type enum, with the input names and the enumerated values.

    >>> letters = enum('a','e','i','o','u','b','c','y','z')
    >>> letters.a < letters.e

    ## index by property
    >>> letters.a

    ## index by position
    >>> letters[0]

    ## index by name, helpful for bridging string inputs to enum
    >>> letters['a']

    ## sorting by order in the enum() create, not character value
    >>> letters.u < letters.b

    ## normal slicing operations available
    >>> letters[-1]

    ## error since there are not 100 items in enum
    >>> letters[99]
    Traceback (most recent call last):
    IndexError: tuple index out of range

    ## error since name does not exist in enum
    >>> letters['ggg']
    Traceback (most recent call last):
    ValueError: tuple.index(x): x not in tuple

    ## enums must be named using valid Python identifiers
    >>> numbers = enum(1,2,3,4)
    Traceback (most recent call last):
    AssertionError: Enum values must be string or unicode

    >>> a = enum('-a','-b')
    Traceback (most recent call last):
    TypeError: Error when calling the metaclass bases
        __slots__ must be identifiers

    ## create another enum
    >>> tags = enum('a','b','c')
    >>> tags.a
    >>> letters.a

    ## can't compare values from different enums
    >>> letters.a == tags.a
    Traceback (most recent call last):
    AssertionError: Only values from the same enum are comparable

    >>> letters.a < tags.a
    Traceback (most recent call last):
    AssertionError: Only values from the same enum are comparable

    ## can't update enum after create
    >>> letters.a = 'x'
    Traceback (most recent call last):
    AttributeError: 'EnumClass' object attribute 'a' is read-only

    ## can't update enum after create
    >>> del letters.u
    Traceback (most recent call last):
    AttributeError: 'EnumClass' object attribute 'u' is read-only

    ## can't have non-unique enum values
    >>> x = enum('a','b','c','a')
    Traceback (most recent call last):
    AssertionError: Enums must not repeat values

    ## can't have zero enum values
    >>> x = enum()
    Traceback (most recent call last):
    AssertionError: Empty enums are not supported

    ## can't have enum values that look like special function names
    ## since these could collide and lead to non-obvious errors
    >>> x = enum('a','b','c','__cmp__')
    Traceback (most recent call last):
    AssertionError: Enum values beginning with __ are not supported

    Enum values of unicode type are not preserved, mapped to ASCII instead.

    ## must have at least one enum value
    assert names, 'Empty enums are not supported'
    ## enum values must be strings
    assert len([i for i in names if not isinstance(i, types.StringTypes) and not \
        isinstance(i, unicode)]) == 0, 'Enum values must be string or unicode'
    ## enum values must not collide with special function names
    assert len([i for i in names if i.startswith("__")]) == 0,\
        'Enum values beginning with __ are not supported'
    ## each enum value must be unique from all others
    assert names == uniquify(names), 'Enums must not repeat values'

    class EnumClass(object):
        """ See parent function for explanation """

        __slots__ = names

        def __iter__(self):
            return iter(constants)

        def __len__(self):
            return len(constants)

        def __getitem__(self, i):
            ## this makes xx['name'] possible
            if isinstance(i, types.StringTypes):
                i = names.index(i)
            ## handles the more normal xx[0]
            return constants[i]

        def __repr__(self):
            return 'enum' + str(names)

        def __str__(self):
            return 'enum ' + str(constants)

        def index(self, i):
            return names.index(i)

    class EnumValue(object):
        """ See parent function for explanation """

        __slots__ = ('__value')

        def __init__(self, value):
            self.__value = value

        value = property(lambda self: self.__value)

        enumtype = property(lambda self: enumtype)

        def __hash__(self):
            return hash(self.__value)

        def __cmp__(self, other):
            assert self.enumtype is other.enumtype, 'Only values from the same enum are comparable'
            return cmp(self.value, other.value)

        def __invert__(self):
            return constants[maximum - self.value]

        def __nonzero__(self):
            ## return bool(self.value)
            ## Original code led to bool(x[0])==False, not correct
            return True

        def __repr__(self):
            return str(names[self.value])

    maximum = len(names) - 1
    constants = [None] * len(names)
    for i, each in enumerate(names):
        val = EnumValue(i)
        setattr(EnumClass, each, val)
        constants[i] = val
    constants = tuple(constants)
    enumtype = EnumClass()
    return enumtype

@Danilo Bargen 2013-05-10 16:09:02

On 2013-05-10, Guido agreed to accept PEP 435 into the Python 3.4 standard library. This means that Python finally has builtin support for enumerations!

There is a backport available for Python 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4. It's on Pypi as enum34.


>>> from enum import Enum
>>> class Color(Enum):
...     red = 1
...     green = 2
...     blue = 3


>>> print(
>>> print(repr(
< 1>


>>> for color in Color:
...   print(color)

Programmatic access:

>>> Color(1)
>>> Color['blue']

For more information, refer to the proposal. Official documentation will probably follow soon.

@SingleNegationElimination 2011-12-22 02:16:04

I have had occasion to need of an Enum class, for the purpose of decoding a binary file format. The features I happened to want is concise enum definition, the ability to freely create instances of the enum by either integer value or string, and a useful representation. Here's what I ended up with:

>>> class Enum(int):
...     def __new__(cls, value):
...         if isinstance(value, str):
...             return getattr(cls, value)
...         elif isinstance(value, int):
...             return cls.__index[value]
...     def __str__(self): return self.__name
...     def __repr__(self): return "%s.%s" % (type(self).__name__, self.__name)
...     class __metaclass__(type):
...         def __new__(mcls, name, bases, attrs):
...             attrs['__slots__'] = ['_Enum__name']
...             cls = type.__new__(mcls, name, bases, attrs)
...             cls._Enum__index = _index = {}
...             for base in reversed(bases):
...                 if hasattr(base, '_Enum__index'):
...                     _index.update(base._Enum__index)
...             # create all of the instances of the new class
...             for attr in attrs.keys():
...                 value = attrs[attr]
...                 if isinstance(value, int):
...                     evalue = int.__new__(cls, value)
...                     evalue._Enum__name = attr
...                     _index[value] = evalue
...                     setattr(cls, attr, evalue)
...             return cls

A whimsical example of using it:

>>> class Citrus(Enum):
...     Lemon = 1
...     Lime = 2
>>> Citrus.Lemon
>>> Citrus(1)
>>> Citrus(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in __new__
KeyError: 5
>>> class Fruit(Citrus):
...     Apple = 3
...     Banana = 4
>>> Fruit.Apple
>>> Fruit.Lemon
>>> Fruit(1)
>>> Fruit(3)
>>> "%d %s %r" % ((Fruit.Apple,)*3)
'3 Apple Fruit.Apple'
>>> Fruit(1) is Citrus.Lemon

Key features:

  • str(), int() and repr() all produce the most useful output possible, respectively the name of the enumartion, its integer value, and a Python expression that evaluates back to the enumeration.
  • Enumerated values returned by the constructor are limited strictly to the predefined values, no accidental enum values.
  • Enumerated values are singletons; they can be strictly compared with is

@xorsyst 2012-08-02 09:37:01

I really like the use of a superclass with its own metaclass, to make it easy to define enums. What's missing here is a __contains__ method. I'd like to be able to check that a given variable is part of the enum - mostly because I want the enums for allowable values of a function parameter.

@SingleNegationElimination 2012-08-02 11:30:51

This is actually a slightly trimmed version of the one I originally created (which you can find here: )v which defines a __instancecheck__ method. Classes are not collections of instances, so 1 in Fruit is absurd. However, the linked version supports isinstance(1, Fruit) which would be more correct in terms of the notion of classes and instances.

@xorsyst 2012-08-06 10:11:40

But forgetting classes and thinking in terms of enums, then it makes sense to think of them as a collection. For example, I might have an enum of file opening modes (MODE.OPEN, MODE.WRITE, etc). I want to verify the parameters to my function: if mode in MODE: reads a lot better than isintance(mode, Mode)

@hans_meine 2017-01-18 08:47:10

I have put up something very similar, which supports more than just ints, and is documented and tested, on GitHub:

@Jah 2012-11-20 13:18:46

I like to use lists or sets as enumerations. For example:

>>> packet_types = ['INIT', 'FINI', 'RECV', 'SEND']
>>> packet_types.index('INIT')
>>> packet_types.index('FINI')

@Oxdeadbeef 2012-06-21 22:43:55

A variant (with support to get an enum value's name) to Alec Thomas's neat answer:

class EnumBase(type):
    def __init__(self, name, base, fields):
        super(EnumBase, self).__init__(name, base, fields)
        self.__mapping = dict((v, k) for k, v in fields.iteritems())
    def __getitem__(self, val):
        return self.__mapping[val]

def enum(*seq, **named):
    enums = dict(zip(seq, range(len(seq))), **named)
    return EnumBase('Enum', (), enums)

Numbers = enum(ONE=1, TWO=2, THREE='three')
print Numbers.TWO
print Numbers[Numbers.ONE]
print Numbers[2]
print Numbers['three']

@jianpx 2012-04-04 02:43:36

I use a metaclass to implement an enumeration (in my thought, it is a const). Here is the code:

class ConstMeta(type):
    Metaclass for some class that store constants
    def __init__(cls, name, bases, dct):
        init class instance
        def static_attrs():
            @rtype: (static_attrs, static_val_set)
            @return: Static attributes in dict format and static value set
            import types
            attrs = {}
            val_set = set()
            #Maybe more
            filter_names = set(['__doc__', '__init__', '__metaclass__', '__module__', '__main__'])
            for key, value in dct.iteritems():
                if type(value) != types.FunctionType and key not in filter_names:
                    if len(value) != 2:
                        raise NotImplementedError('not support for values that is not 2 elements!')
                    #Check value[0] duplication.
                    if value[0] not in val_set:
                        raise KeyError("%s 's key: %s is duplicated!" % (dict([(key, value)]), value[0]))
                    attrs[key] = value
            return attrs, val_set

        attrs, val_set = static_attrs()
        #Set STATIC_ATTRS to class instance so that can reuse
        setattr(cls, 'STATIC_ATTRS', attrs)
        setattr(cls, 'static_val_set', val_set)
        super(ConstMeta, cls).__init__(name, bases, dct)

    def __getattribute__(cls, name):
        Rewrite the special function so as to get correct attribute value
        static_attrs = object.__getattribute__(cls, 'STATIC_ATTRS')
        if name in static_attrs:
            return static_attrs[name][0]
        return object.__getattribute__(cls, name)

    def static_values(cls):
        Put values in static attribute into a list, use the function to validate value.
        @return: Set of values
        return cls.static_val_set

    def __getitem__(cls, key):
        Rewrite to make syntax SomeConstClass[key] works, and return desc string of related static value.
        @return: Desc string of related static value
        for k, v in cls.STATIC_ATTRS.iteritems():
            if v[0] == key:
                return v[1]
        raise KeyError('Key: %s does not exists in %s !' % (str(key), repr(cls)))

class Const(object):
    Base class for constant class.


    Definition: (must inherit from Const class!
        >>> class SomeConst(Const):
        >>>   STATUS_NAME_1 = (1, 'desc for the status1')
        >>>   STATUS_NAME_2 = (2, 'desc for the status2')

    Invoke(base upper SomeConst class):
    1) SomeConst.STATUS_NAME_1 returns 1
    2) SomeConst[1] returns 'desc for the status1'
    3) SomeConst.STATIC_ATTRS returns {'STATUS_NAME_1': (1, 'desc for the status1'), 'STATUS_NAME_2': (2, 'desc for the status2')}
    4) SomeConst.static_values() returns set([1, 2])

    SomeCosnt's value 1, 2 can not be duplicated!
    If WrongConst is like this, it will raise KeyError:
    class WrongConst(Const):
        STATUS_NAME_1 = (1, 'desc for the status1')
        STATUS_NAME_2 = (1, 'desc for the status2')
    __metaclass__ = ConstMeta
#Const Base Class ends

def main():
    class STATUS(Const):
        ERROR = (-3, '??')
        OK = (0, '??')

    print STATUS.ERROR
    print STATUS.static_values()

    #Usage sample:
    user_input = 1
    #Validate input:
    print user_input in STATUS.static_values()
    #Template render like:
    print '<select>'
    for key, value in STATUS.STATIC_ATTRS.items():
        print '<option value="%s">%s</option>' % (value[0], value[1])
    print '</select>'

if __name__ == '__main__':

@daegga 2010-06-04 16:33:27

I like the Java enum, that's how I do it in Python:

def enum(clsdef):
    class Enum(object):
        __slots__=tuple([var for var in clsdef.__dict__ if isinstance((getattr(clsdef, var)), tuple) and not var.startswith('__')])

        def __new__(cls, *args, **kwargs):
            if not '_the_instance' in cls.__dict__:
                cls._the_instance = object.__new__(cls, *args, **kwargs)
            return cls._the_instance

        def __init__(self):
            clsdef.values=lambda cls, e=Enum: e.values()
            clsdef.valueOf=lambda cls, n, e=self: e.valueOf(n)
            for ordinal, key in enumerate(self.__class__.__slots__):
                args=getattr(clsdef, key)
                setattr(self, key, instance)

        def values(cls):
            if not hasattr(cls, '_values'):
                cls._values=[getattr(cls, name) for name in cls.__slots__]
            return cls._values

        def valueOf(self, name):
            return getattr(self, name)

        def __repr__(self):
            return ''.join(['<class Enum (', clsdef.__name__, ') at ', str(hex(id(self))), '>'])

    return Enum()

Sample use:

class Test(object):

    while True:
            F, G, H, I, J, K, L, M, N, O=[tuple() for _ in range(i)]
        except ValueError:

    def __init__(self, name="default", aparam=0):

All class variables are defined as a tuple, just like the constructor. So far, you can't use named arguments.

@daegga 2010-06-04 16:42:55

python3k btw, don't know if it runs on 2.x

@L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳ 2010-05-07 02:05:03

Why must enumerations be ints? Unfortunately, I can't think of any good looking construct to produce this without changing the Python language, so I'll use strings:

class Enumerator(object):
    def __init__(self, name): = name

    def __eq__(self, other):
        if == other:
            return True
        return self is other

    def __ne__(self, other):
        if != other:
            return False
        return self is other

    def __repr__(self):
        return 'Enumerator({0})'.format(

    def __str__(self):

class Enum(object):
    def __init__(self, *enumerators):
        for e in enumerators:
            setattr(self, e, Enumerator(e))
    def __getitem__(self, key):
        return getattr(self, key)

Then again maybe it's even better now that we can naturally test against strings, for the sake of configuration files or other remote input.


class Cow(object):
    State = Enum(
    state = State.standing

In [1]: from enum import Enum

In [2]: c = Cow()

In [3]: c2 = Cow()

In [4]: c.state, c2.state
Out[4]: (Enumerator(standing), Enumerator(standing))

In [5]: c.state == c2.state
Out[5]: True

In [6]: c.State.mooing
Out[6]: Enumerator(mooing)

In [7]: c.State['mooing']
Out[7]: Enumerator(mooing)

In [8]: c.state = Cow.State.dead

In [9]: c.state == c2.state
Out[9]: False

In [10]: c.state == Cow.State.dead
Out[10]: True

In [11]: c.state == 'dead'
Out[11]: True

In [12]: c.state == Cow.State['dead']
Out[11]: True

@wim 2014-02-11 15:58:54

If you have integer field in a mysql db you often want int enums

@pythonic metaphor 2010-03-16 22:36:42

The enum package from PyPI provides a robust implementation of enums. An earlier answer mentioned PEP 354; this was rejected but the proposal was implemented

Usage is easy and elegant:

>>> from enum import Enum
>>> Colors = Enum('red', 'blue', 'green')
>>> shirt_color =
>>> shirt_color = Colors[2]
>>> shirt_color >
>>> shirt_color.index
>>> str(shirt_color)

@iobaixas 2010-03-05 20:24:21

Following the Java like enum implementation proposed by Aaron Maenpaa, I came out with the following. The idea was to make it generic and parseable.

class Enum:
    #Java like implementation for enums.
    #class Tool(Enum): name = 'Tool'
    #Tool.DRILL = Tool.register('drill')
    #Tool.HAMMER = Tool.register('hammer')
    #Tool.WRENCH = Tool.register('wrench')

    name = 'Enum'    # Enum name
    _reg = dict([])   # Enum registered values

    def register(cls, value):
        #Registers a new value in this enum.
        #@param value: New enum value.
        #@return: New value wrapper instance.
        inst = cls(value)
        cls._reg[value] = inst
        return inst

    def parse(cls, value):
        #Parses a value, returning the enum instance.
        #@param value: Enum value.
        #@return: Value corresp instance.        
        return cls._reg.get(value)    

    def __init__(self, value):
        #Constructor (only for internal use).
        self.value = value

    def __str__(self):
        #str() overload.
        return self.value

    def __repr__(self):
        #repr() overload.
        return "<" + + ": " + self.value + ">"

@Tony Veijalainen 2010-07-20 16:00:27

I can not understand how this repr could be used to reproduce the object.

@REINSTATE MONICA -Jeremy Banks 2011-07-26 04:34:13

@Tony it is not required to do so, though it is a good thing.

@Natim 2009-10-19 10:21:39

Use the following.

TYPE = {'EAN13':   u'EAN-13',
        'CODE39':  u'Code 39',
        'CODE128': u'Code 128',
        'i25':     u'Interleaved 2 of 5',}

>>> TYPE.items()
[('EAN13', u'EAN-13'), ('i25', u'Interleaved 2 of 5'), ('CODE39', u'Code 39'), ('CODE128', u'Code 128')]
>>> TYPE.keys()
['EAN13', 'i25', 'CODE39', 'CODE128']
>>> TYPE.values()
[u'EAN-13', u'Interleaved 2 of 5', u'Code 39', u'Code 128']

I used that for Django model choices, and it looks very pythonic. It is not really an Enum, but it does the job.

@Jake 2008-10-21 02:08:29

It's funny, I just had a need for this the other day and I couldnt find an implementation worth using... so I wrote my own:

import functools

class EnumValue(object):
    def __init__(self,name,value,type):
    def __str__(self):
        return self.__name
    def __repr__(self):#2.6 only... so change to what ever you need...
        return '{cls}({0!r},{1!r},{2})'.format(self.__name,self.__value,self.Type.__name__,cls=type(self).__name__)

    def __hash__(self):
        return hash(self.__value)
    def __nonzero__(self):
        return bool(self.__value)
    def __cmp__(self,other):
        if isinstance(other,EnumValue):
            return cmp(self.__value,other.__value)
            return cmp(self.__value,other)#hopefully their the same type... but who cares?
    def __or__(self,other):
        if other is None:
            return self
        elif type(self) is not type(other):
            raise TypeError()
        return EnumValue('{0.Name} | {1.Name}'.format(self,other),self.Value|other.Value,self.Type)
    def __and__(self,other):
        if other is None:
            return self
        elif type(self) is not type(other):
            raise TypeError()
        return EnumValue('{0.Name} & {1.Name}'.format(self,other),self.Value&other.Value,self.Type)
    def __contains__(self,other):
        if self.Value==other.Value:
            return True
        return bool(self&other)
    def __invert__(self):
        return functools.reduce(EnumValue.__or__,(enum for enum in enumerables.itervalues() if enum not in self))

    def Name(self):
        return self.__name

    def Value(self):
        return self.__value

class EnumMeta(type):
    def __addToReverseLookup(rev,value,newKeys,nextIter,force=True):
        if value in rev:
            forced,items=rev.get(value,(force,()) )
            if forced and force: #value was forced, so just append
            elif not forced:#move it to a new spot
            else: #not forcing this value
                next =
        else:#set it and forget it
        return value

    def __init__(cls,name,bases,atts):
        enums = classVars.get('__enumerables__',None)
        nextIter = getattr(cls,'__nextitr__',itertools.count)()

        if enums is not None:
            #build reverse lookup
            for item in enums:
                if isinstance(item,(tuple,list)):
                    value=EnumMeta.__addToReverseLookup(reverseLookup,value,(str(item),),nextIter,False)#add it to the reverse lookup, but don't force it to that value

            #build values and clean up reverse lookup
            for value,fkeys in reverseLookup.iteritems():
                for key in keys:
                reverseLookup[value]=tuple(val for val in values.itervalues() if val.Value == value)
        setattr(cls,'_Max',max([key for key in reverseLookup] or [0]))
        return super(EnumMeta,cls).__init__(name,bases,atts)

    def __iter__(cls):
        for enum in cls.__enumerables__.itervalues():
            yield enum
    def GetEnumByName(cls,name):
        return cls.__enumerables__.get(name,None)
    def GetEnumByValue(cls,value):
        return cls.__reverseLookup__.get(value,(None,))[0]

class Enum(object):

class FlagEnum(Enum):
    def __nextitr__():
        yield 0
        for val in itertools.count():
            yield 2**val

def enum(name,*args):
    return EnumMeta(name,(Enum,),dict(__enumerables__=args))

Take it or leave it, it did what I needed it to do :)

Use it like:

class Air(FlagEnum):

class Mammals(Enum):
Bool = enum('Bool','Yes',('No',0))

@abarnert 2013-04-19 01:16:20

While the original enum proposal, PEP 354, was rejected years ago, it keeps coming back up. Some kind of enum was intended to be added to 3.2, but it got pushed back to 3.3 and then forgotten. And now there's a PEP 435 intended for inclusion in Python 3.4. The reference implementation of PEP 435 is flufl.enum.

As of April 2013, there seems to be a general consensus that something should be added to the standard library in 3.4—as long as people can agree on what that "something" should be. That's the hard part. See the threads starting here and here, and a half dozen other threads in the early months of 2013.

Meanwhile, every time this comes up, a slew of new designs and implementations appear on PyPI, ActiveState, etc., so if you don't like the FLUFL design, try a PyPI search.

@FDS 2013-04-08 18:58:52

Python 2.7 and find_name()

Here is an easy-to-read implementation of the chosen idea with some helper methods, which perhaps are more Pythonic and cleaner to use than "reverse_mapping". Requires Python >= 2.7.

To address some comments below, Enums are quite useful to prevent spelling mistakes in code, e.g. for state machines, error classifiers, etc.

def Enum(*sequential, **named):
  """Generate a new enum type. Usage example:

  ErrorClass = Enum('STOP','GO')
  print ErrorClass.find_name(ErrorClass.STOP)
    = "STOP"
  print ErrorClass.find_val("STOP")
    = 0
  ErrorClass.FOO     # Raises AttributeError
  enums = { v:k for k,v in enumerate(sequential) } if not named else named

  def find_name(cls, val):
    result = [ k for k,v in cls.__dict__.iteritems() if v == val ]
    if not len(result):
        raise ValueError("Value %s not found in Enum" % val)
    return result[0]

  def find_val(cls, n):
    return getattr(cls, n)

  enums['find_val'] = find_val
  enums['find_name'] = find_name
  return type('Enum', (), enums)

@user18695 2008-09-20 11:49:38

def M_add_class_attribs(attribs):
    def foo(name, bases, dict_):
        for v, k in attribs:
            dict_[k] = v
        return type(name, bases, dict_)
    return foo

def enum(*names):
    class Foo(object):
        __metaclass__ = M_add_class_attribs(enumerate(names))
        def __setattr__(self, name, value):  # this makes it read-only
            raise NotImplementedError
    return Foo()

Use it like this:

Animal = enum('DOG', 'CAT')
Animal.DOG # returns 0
Animal.CAT # returns 1
Animal.DOG = 2 # raises NotImplementedError

if you just want unique symbols and don't care about the values, replace this line:

__metaclass__ = M_add_class_attribs(enumerate(names))

with this:

__metaclass__ = M_add_class_attribs((object(), name) for name in names)

@Chris Lutz 2009-11-18 02:56:39

IMHO it would be cleaner if you changed enum(names) to enum(*names) - then you could drop the extra parenthesis when calling it.

@Ted Mielczarek 2010-05-28 12:01:50

I like this approach. I actually changed it to set the attribute value to the same string as the name, which has the nice property that Animal.DOG == 'DOG', so they stringify themselves for you automatically. (Helps immensely for printing out debug output.)

@Noctis Skytower 2013-01-31 14:27:43

The solution that I usually use is this simple function to get an instance of a dynamically created class.

def enum(names):
    "Create a simple enumeration having similarities to C."
    return type('enum', (), dict(map(reversed, enumerate(
        names.replace(',', ' ').split())), __slots__=()))()

Using it is as simple as calling the function with a string having the names that you want to reference.

grade = enum('A B C D F')
state = enum('awake, sleeping, dead')

The values are just integers, so you can take advantage of that if desired (just like in the C language).

>>> grade.A
>>> grade.B
>>> grade.F == 4
>>> state.dead == 2

@Zoetic 2012-02-08 20:59:58

An Enum class can be a one-liner.

class Enum(tuple): __getattr__ = tuple.index

How to use it (forward and reverse lookup, keys, values, items, etc.)

>>> State = Enum(['Unclaimed', 'Claimed'])
>>> State.Claimed
>>> State[1]
>>> State
('Unclaimed', 'Claimed')
>>> range(len(State))
[0, 1]
>>> [(k, State[k]) for k in range(len(State))]
[(0, 'Unclaimed'), (1, 'Claimed')]
>>> [(k, getattr(State, k)) for k in State]
[('Unclaimed', 0), ('Claimed', 1)]

@Massimo 2017-07-11 12:37:50

I think it is the simplest end most elegant solution. In python 2.4 ( yes, old legacy server ) tuples haven't index. I solved replacing with list.

@user5920660 2017-07-20 18:04:11

I tried this in a Jupyter notebook and discovered that it wouldn't work as a one-line definition, but that putting the getattr definition on a second (indented) line would be accepted.

@Farzad Abdolhosseini 2019-07-08 23:34:16

This solution let's me use the in keyword to search for members which is neat. Example usage: 'Claimed' in Enum(['Unclaimed', 'Claimed'])

@bj0 2012-01-18 06:09:18

I really like Alec Thomas' solution (

def enum(**enums):
    '''simple constant "enums"'''
    return type('Enum', (object,), enums)

It's elegant and clean looking, but it's just a function that creates a class with the specified attributes.

With a little modification to the function, we can get it to act a little more 'enumy':

NOTE: I created the following examples by trying to reproduce the behavior of pygtk's new style 'enums' (like Gtk.MessageType.WARNING)

def enum_base(t, **enums):
    '''enums with a base class'''
    T = type('Enum', (t,), {})
    for key,val in enums.items():
        setattr(T, key, T(val))

    return T

This creates an enum based off a specified type. In addition to giving attribute access like the previous function, it behaves as you would expect an Enum to with respect to types. It also inherits the base class.

For example, integer enums:

>>> Numbers = enum_base(int, ONE=1, TWO=2, THREE=3)
>>> Numbers.ONE
>>> x = Numbers.TWO
>>> 10 + x
>>> type(Numbers)
<type 'type'>
>>> type(Numbers.ONE)
<class 'Enum'>
>>> isinstance(x, Numbers)

Another interesting thing that can be done with this method is customize specific behavior by overriding built-in methods:

def enum_repr(t, **enums):
    '''enums with a base class and repr() output'''
    class Enum(t):
        def __repr__(self):
            return '<enum {0} of type Enum({1})>'.format(self._name, t.__name__)

    for key,val in enums.items():
        i = Enum(val)
        i._name = key
        setattr(Enum, key, i)

    return Enum

>>> Numbers = enum_repr(int, ONE=1, TWO=2, THREE=3)
>>> repr(Numbers.ONE)
'<enum ONE of type Enum(int)>'
>>> str(Numbers.ONE)

@MestreLion 2013-05-23 04:28:50

this "base" type idea is neat :)

@bj0 2013-05-25 08:23:35

yea, note that you can also do this with the new Python 3.4 Enum:

Related Questions

Sponsored Content

16 Answered Questions

[SOLVED] What are metaclasses in Python?

62 Answered Questions

[SOLVED] Calling an external command from Python

21 Answered Questions

[SOLVED] How do I list all files of a directory?

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 3691200 View
  • 3474 Score
  • 21 Answer
  • Tags:   python directory

41 Answered Questions

[SOLVED] How do I merge two dictionaries in a single expression?

17 Answered Questions

[SOLVED] How to make a chain of function decorators?

27 Answered Questions

[SOLVED] How to cast int to enum?

  • 2008-08-27 03:58:21
  • lomaxx
  • 1266769 View
  • 2991 Score
  • 27 Answer
  • Tags:   c# enums casting

27 Answered Questions

[SOLVED] How to enumerate an enum?

39 Answered Questions

[SOLVED] How to print colored text in terminal in Python?

25 Answered Questions

[SOLVED] How can I safely create a nested directory?

8 Answered Questions

[SOLVED] How to loop through all enum values in C#?

Sponsored Content