Python Enum with multiple attributes

Question:

I have his Enum :

class MultiAttr(Enum):
    RED = (1, 10)
    GREEN = (2, 20)
    BLUE = (3, 20)
    def __init__(self, id, val):
        self.id = id
        self.val = val
assert MultiAttr((2, 20)) == MultiAttr.GREEN

Assertion passes.

  1. Why Pylance in VSCode complains Argument missing for parameter "val" ?
  2. As the first attribute is the identifer, is there a way to achieve :
    MultiAttr(2) == MultiAttr.GREEN ?
Asked By: Philippe

||

Answers:

You could make use of __new__, as you want to customize the actual value of the Enum member:

from enum import Enum

class MultiAttr(bytes, Enum):
    def __new__(cls, value, otherVal):
        obj = bytes.__new__(cls, [value])
        obj._value_ = value
        obj.otherVal = otherVal
        return obj
    RED = (1, 10)
    GREEN = (2, 20)
    BLUE = (3, 20)


print(MultiAttr(2) == MultiAttr.GREEN)
print(MultiAttr(2).otherVal)

Out:

True
20
Answered By: Maurice Meyer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.