Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python enum iteration over subset

Tags:

I would like to iterate over a subset of the following enum

class Items(enum.Enum):
    item1 = 0
    item2 = 1
    item3 = 2
    item4 = 3
    item5 = 4
    itm66 = 5
    item7 = 6
    item8 = 7

Say I want to:

for item in (Items.item1, Items.item2, Items.item3, Items.item4):
        print(item.value)

is there a shortcut? or do I need to list each item to iterate over?

like image 203
Fred Avatar asked Oct 23 '18 20:10

Fred


People also ask

What is Auto () in Python?

auto() method, we can get the assigned integer value automatically by just using enum. auto() method. Syntax : enum.auto() Automatically assign the integer value to the values of enum class attributes.

Is enum ordered Python?

Because Python's enum. Enum does not provide ordering by default, ostensibly to eliminate C-style (mis-)treatment of enumerations as thin wrappers over integral types.

Should enums be capitalized Python?

Notice that enumerations are not normal Python classes, even though they are defined in a similar way. As enumerations are meant to represent constant values, it is advisable to uppercase the enum member names.

How does enum work in Python?

Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over.


2 Answers

Using itertools.islice you can iterate through a slice of your Enum class

from enum import Enum
from itertools import islice

class Items(Enum):
    item1 = 0
    item2 = 1
    item3 = 2
    item4 = 3
    item5 = 4
    itm66 = 5
    item7 = 6
    item8 = 7

for i in islice(Items, 4):
    print(i.value)

# 0 
# 1 
# 2
# 3
like image 102
vash_the_stampede Avatar answered Sep 25 '22 19:09

vash_the_stampede


Python enums can have methods. I'd suggest you write a method that returns an iterable. Probably a set, in this case:

class Items(enum.Enum):
    item1 = 0
    item2 = 1
    item3 = 2
    item4 = 3
    item5 = 4
    itm66 = 5
    item7 = 6
    item8 = 7

    @classmethod
    def the_best_ones(cls):
        return cls.item1, cls.item2, cls.item3, cls.item4

Then:

for item in Items.the_best_ones():
    print(item.value)
like image 34
aghast Avatar answered Sep 22 '22 19:09

aghast