Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 887
iago-lito Avatar asked Dec 26 '15 10:12

iago-lito


People also ask

What is enum Auto ()?

Syntax : enum.auto() Automatically assign the integer value to the values of enum class attributes. Example #1 : In this example we can see that by using enum. auto() method, we are able to assign the numerical values automatically to the class attributes by using this method.

Can enum have multiple values python?

Enums can't have multiple value per name.

Can enums contain numbers?

Numeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.


2 Answers

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 
like image 106
Ethan Furman Avatar answered Sep 22 '22 12:09

Ethan Furman


Did you try print(len(Mood)) ?

like image 37
DeepSpace Avatar answered Sep 22 '22 12:09

DeepSpace