Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Enum item as a list index

I Have this piece of code :

class FileType(Enum):
    BASIC = 0
    BASIC_CORRUPTED = 1
    BASIC_SHITTY_END = 2
    MIMIKATZ = 3
    HASHCAT = 4

    def __eq__(self, v):
        """
        Override == in order to make `FileType.BASIC == 0` equals to True, etc.
        """
        return self.value == v if isinstance(v, int) else self.value == v.value

I wonder what I should add if I want to perform this: random_array[FileType.MIMIKATZ]. Currently, Python3 tells me TypeError: list indices must be integers or slices, not FileType

like image 793
Chocorean Avatar asked Jun 18 '19 14:06

Chocorean


People also ask

Can you use enum as index?

It is perfectly normal to use an enum for indexing into an array. You don't have to specify each enum value, they will increment automatically by 1. Letting the compiler pick the values reduces the possibility of mistyping and creating a bug, but it deprives you of seeing the values, which might be useful in debugging.

Can you index an enum in C?

You can't do that. A C enum is not much more than a bunch of constants. There's no type-safety or reflection that you might get in a C# or Java enum . Show activity on this post.

Can we create list of enums?

In Java 10 and later, you can conveniently create a non-modifiable List by passing the EnumSet . The order of the new list will be in the iterator order of the EnumSet . The iterator order of an EnumSet is the order in which the element objects of the enum were defined on that enum. Great insight in this answer!

What is Auto () in Python?

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


1 Answers

Your class should inherit from IntEnum instead, this supports integer like behaviour. From the docs,

Members of an IntEnum can be compared to integers; by extension, integer enumerations of different types can also be compared to each other:

from enum import IntEnum

class FileType(IntEnum):
    BASIC = 0
    BASIC_CORRUPTED = 1
    BASIC_SHITTY_END = 2
    MIMIKATZ = 3
    HASHCAT = 4

You can now use an enum constant to index your list,

data = [1, 2, 3, 4]
data[FileType.MIMIKATZ]
# 4
like image 99
cs95 Avatar answered Sep 22 '22 05:09

cs95