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.
- Why Pylance in VSCode complains
Argument missing for parameter "val"
?
- As the first attribute is the identifer, is there a way to achieve :
MultiAttr(2) == MultiAttr.GREEN
?
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
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.
- Why Pylance in VSCode complains
Argument missing for parameter "val"
? - As the first attribute is the identifer, is there a way to achieve :
MultiAttr(2) == MultiAttr.GREEN
?
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