Is there a dedicated way to get the number of items in a python `Enum`?


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?

Asked By: iago-lito



Did you try print(len(Mood)) ?

Answered By: DeepSpace

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

# [<Example.this: 1>, <Example.that: 2>, <Example.those: 3>]

# Example.this

# Example.this

# Example.this
Answered By: Ethan Furman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.