40

Say I have such a python Enum class:

from enum import Enum

class Mood(Enum):
    red = 0
    green = 1
    blue = 2

Is there a natural way to get the total number of items in Mood? (like without having to iterate over it, or to add an extra n item, or an extra n classproperty, etc.)

Does the enum module provide such a functionality?

Community
  • 1
  • 1
iago-lito
  • 3,098
  • 3
  • 29
  • 54

2 Answers2

65

Yes. Enums have several extra abilities that normal classes do not:

class Example(Enum):
    this = 1
    that = 2
    dupe = 1
    those = 3

print(len(Example))  # duplicates are not counted
# 3

print(list(Example))
# [<Example.this: 1>, <Example.that: 2>, <Example.those: 3>]

print(Example['this'])
# Example.this

print(Example['dupe'])
# Example.this

print(Example(1))
# Example.this
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • My enum (Python 3.4) is not static but created as presented [here](http://stackoverflow.com/a/1695250/150978) (the one form automatic enumeration) and the last three commands do not work for such an enum. Are there different enum-implementations in Python? – Robert Apr 28 '16 at 10:54
  • There is a third-party library called `enum` that is **not** the same as the official 3.4 `Enum`, nor it's [backport](https://pypi.python.org/pypi/enum34) and [advanced](https://pypi.python.org/pypi/aenum) versions. Whatever `enum` you are using is not one of the three new ones. – Ethan Furman Apr 28 '16 at 14:54
11

Did you try print(len(Mood)) ?

DeepSpace
  • 78,697
  • 11
  • 109
  • 154