Can I create an Enum of a dataclass instances?

Viewed 559

I have a fixed set of three sensors that I want to model as an enum. Each of these sensors is parametrised by a few different attributes. I therefore want to model the sensors themselves as a dataclass.

My naive attempt looks something like this:

@dataclass
class SensorLocation:
    address: int
    pins: int
    other_details: ...

class Sensors(SensorLocation, Enum):
    TOP_SENSOR = SensorLocation(address=0x10, pins=0xf,  other_details=...)
    BOTTOM_SENSOR = SensorLocation(address=0x10, pins=0xf0,  other_details=...)
    SIDE_SENSOR = SensorLocation(address=0x15, pins=0xf,  other_details=...)

My expectation is that this should essentially create an enum, where the instances of that enum behave like instances of SensorLocation. This makes the types a bit clearer and puts methods where I'd expect them to be.

However, this fails while creating the enum, with the error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/to/python/3.7.10/lib/python3.7/enum.py", line 232, in __new__
    enum_member.__init__(*args)
  File "<string>", line 3, in __init__
  File "/path/to/python/3.7.10/lib/python3.7/types.py", line 175, in __set__
    raise AttributeError("can't set attribute")
AttributeError: can't set attribute

What I can do is remove the SensorLocation subclassing in the enum declaration, but this means that when using MyPy or similar tools, I lose some ability to type hint the correct values. It also makes accessing the actual values more complicated, but the main purpose of this enum is to provide access to those values.

Is there a way around this error that I'm missing, or another solution that I can't see right now?

0 Answers
Related