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
Enumin a way other than which it was intended. Let me explain:First, an enum with more useful names:
Each enum member (so
APPLEandBANANAabove) is a singleton -- there will only ever be oneFood.APPLE, oneFood.BANANA, and oneFood.CARROT(if you add it). If you add anxandyattribute toFood.CARROT, then everywhere you useFood.CARROTyou will see whateverxandywere last set to.For example, if
func1callsfunc2withFood.CARROT(17, 19), andfunc2callsfunc3withFood.CARROT(99, 101), then whenfunc1regains control it will seeFood.CARROT.x == 99andFood.CARROT.y == 101.The way to solve this particular problem is just to add the
xandyparameters to your functions, and have the functions verify them (just like you would for any other parameter that had restrictions or requirements).