3

I have an enum that should be something like this:

from enum import Enum


class ComponentType(Enum):
    5120 = "<{}b"
    5121 = "<{}B"
    5122 = "<{}h"
    5123 = "<{}H"
    5125 = "<{}I"
    5126 = "<{}f"

Obviously, this doesn't work because you can't assign to a literal. How would I go about creating and using an enum from this data? I have an integer that needs to pair with a format for struct.unpack(). I know this can be done with a dictionary, can it be done with an enum? What would it look like?

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
H6aGyZab
  • 31
  • 1
  • Please try to avoid "this" in question titles so people don't need to click through and read the body before they can have even a rough idea of what your question is about. (I've edited the title towards that end). – Charles Duffy May 05 '22 at 01:51

1 Answers1

2

A dictionary is your best option here. The enum names become attributes of the class, and an integer cannot be the name of an attribute.

If you really want to use an enum, you could make the names into valid attribute names, like by prepending an arbitrary letter.

class ComponentType(Enum):
    s5120 = "<{}b"
    s5121 = "<{}B"
    s5122 = "<{}h"
    s5123 = "<{}H"
    s5125 = "<{}I"
    s5126 = "<{}f"

ComponentType.s5120.value  # '<{}b'
jkr
  • 17,119
  • 2
  • 42
  • 68