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?
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.
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.
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With