iago-lito
iago-lito

Reputation: 3218

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?

Upvotes: 47

Views: 30148

Answers (2)

Ethan Furman
Ethan Furman

Reputation: 69041

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

Upvotes: 74

DeepSpace
DeepSpace

Reputation: 81604

Did you try print(len(Mood)) ?

Upvotes: 11

Related Questions