I have a Python enum:
class E(Enum):
A = 1
B = 2
It is part of a public interface, people pass E.A
or E.B
to various functions to specify some parameter. I want to augment this enum to add a third value, C
, but this value only makes sense if you also pass a couple of additional parameters, x
and y
. So in addition to allowing my users to pass E.A
or E.B
, I want them to be able to pass e.g. E.C(x=17,y=42)
, and have my code access the values of these parameters (here, 17 and 42).
What's the most "pythonic" way of achieving this? I'm using Python 3.7.
There is no Pythonic way to achieve this, as you are trying to use
Enum
in a way other than which it was intended. Let me explain:First, an enum with more useful names:
Each enum member (so
APPLE
andBANANA
above) is a singleton -- there will only ever be oneFood.APPLE
, oneFood.BANANA
, and oneFood.CARROT
(if you add it). If you add anx
andy
attribute toFood.CARROT
, then everywhere you useFood.CARROT
you will see whateverx
andy
were last set to.For example, if
func1
callsfunc2
withFood.CARROT(17, 19)
, andfunc2
callsfunc3
withFood.CARROT(99, 101)
, then whenfunc1
regains control it will seeFood.CARROT.x == 99
andFood.CARROT.y == 101
.The way to solve this particular problem is just to add the
x
andy
parameters to your functions, and have the functions verify them (just like you would for any other parameter that had restrictions or requirements).