Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an enum with numeric keys? [duplicate]

Tags:

python

enums

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?

like image 466
H6aGyZab Avatar asked Sep 15 '25 13:09

H6aGyZab


1 Answers

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'
like image 50
jakub Avatar answered Sep 18 '25 10:09

jakub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!